iT邦幫忙

0

【C#】Creational Patterns Abstract Factory Mode

c#
  • 分享至 

  • xImage
  •  

The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.


學習目標: 抽象工廠模式的概念及實務

學習難度: ☆☆☆


using System;

namespace ConsoleApp1
{
    abstract class GameFactory //抽象工廠
    {
        public abstract RTS CreateRTS();
        
        public abstract FPS CreateFPS();
    }

    class Department : GameFactory //具體工廠(部門)
    {
        public override RTS CreateRTS()
        {
            Console.WriteLine("AOE3已生產");

            return new AOE3();
        }

        public override FPS CreateFPS()
        {
            Console.WriteLine("CSO已生產");

            return new CSO();
        }
    }

    abstract class RTS //抽象產品
    {
        public abstract string name { get; set; }

        public abstract int price { get; set; }

        public abstract void Demo();
    }

    class AOE3 : RTS //具體產品
    {
        public override string name { get; set; } = "AOE3";

        public override int price { get; set; } = 300;

        public override void Demo()
        {
            Console.WriteLine("This is  AOE3 game");
        }
    }

    abstract class FPS //抽象產品
    {
        public abstract string name { get; set; }

        public abstract int price { get; set; }

        public abstract void Demo();
    }


    class CSO : FPS //具體產品
    {
        public override string name { get; set; } = "CSO";

        public override int price { get; set; } = 100;

        public override void Demo()
        {
            Console.WriteLine("This is  CSO game");
        }
    }

    class Steam //客戶端(串接工廠and產品)
    {
        public RTS AOE3; public FPS CSO;

        public Steam(GameFactory factory) //Steam上架...
        {
            AOE3 = factory.CreateRTS();

            CSO = factory.CreateFPS();
        }
    }

    class MainProgram
    {
        public static void Main()
        {
            GameFactory department = new Department();

            Steam steam = new Steam(department);       
        }
    }
}

參考資料:

https://www.dofactory.com/net/abstract-factory-design-pattern


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言