工廠方法-Factory Method Pattern

工廠方法

目的:提供一個工廠介面,將產生實體程式碼交由子類別各自實現。

工廠方法是延伸了簡單工廠,因為簡單工廠會破壞OCP原則。

優點:
1.只需關心對應工廠,無須關心創建細節。
2.符合閉關原則,只需新增工廠類別與產品,無須修改程式,擴展性佳。

缺點:
1.因為添加新的產品或類別,增加系統複雜度。
2.考量到系統可擴展性,需引入抽象層,增加了系統抽象和理解難度。
 

    class Program
    {
        static void Main(string[] args)
        {
            Creator[] creators = new Creator[2];
            creators[0] = new ConcreCreatorA();
            creators[1] = new ConcreCreatorB();
            foreach (var creator in creators)
            {
                Product product = creator.FactoryMethod();
                Console.WriteLine(product.GetType().Name);
            }
        }
    }

    abstract class Product
    {

    }

    class ConcreateProductA : Product
    {

    }

    class ConcreateProductB : Product
    {

    }

    abstract class Creator
    {
        public abstract Product FactoryMethod();
    }

    class ConcreCreatorA : Creator
    {
        public override Product FactoryMethod()
        {
            return new ConcreateProductA();
        }
    }

    class ConcreCreatorB : Creator
    {
        public override Product FactoryMethod()
        {
            return new ConcreateProductB();
        }
    }

 

    abstract class Product
    {
    }

    class ConcreateProductA : Product
    {
    }

    class ConcreateProductB : Product
    {
    }

    interface Ifactory
    {
        Product CreateProduct();
    }

    class ConcreCreatorAFactory : Ifactory
    {
        public Product CreateProduct()
        {
            Console.WriteLine("A");
            return new ConcreateProductA();
        }
    }

    class ConcreCreatorBFactory : Ifactory
    {
        public Product CreateProduct()
        {
            Console.WriteLine("B");
            return new ConcreateProductB();
        }
    }

元哥的筆記