1. 程式人生 > >工廠模式(Factory Method Pattern)

工廠模式(Factory Method Pattern)

n) 多態 產品 tel att new strac 代碼結構 減少

模式定義

工廠方法模式(Factory Method Pattern)又稱為工廠模式,也叫虛擬構造器(Virtual Constructor)模式或者多態工廠(Polymorphic Factory)模式,它屬於類創建型模式。在工廠方法模式中,工廠父類負責定義創建產品對象的公共接口,而工廠子類則負責生成具體的產品對象,這樣做的目的是將產品類的實例化操作延遲到工廠子類中完成,即通過工廠子類來確定究竟應該實例化哪一個具體產品類。

UML類圖

技術分享圖片

  • Product 抽象產品
  • ConcreteProduct 具體產品
  • Factory 抽象工廠
  • ConcreteFactory 具體工廠

    代碼結構組成

    public  class FactoryApp
    {
        public static void Run()
        {
            Creator[] creators = new Creator[2];
    
            creators[0] = new ConcreteCreatorA();
            creators[1] = new ConcreteCreatorB();
    
            foreach(Creator creator in creators)
            {
                Product product = creator.FactoryMothed();
                Console.WriteLine("Created {0}", product.GetType().Name);
            }
        }
    }
    
    public class Product
    { }
    public class ConcreteProductA:Product
    { }
    public class ConcreteProductB:Product
    { }
    
    public abstract class Creator
    {
        public abstract Product FactoryMothed();
    }
    
    public class ConcreteCreatorA:Creator
    {
        public override Product FactoryMothed()
        {
            return new ConcreteProductA();
        }
    }
    
    public class ConcreteCreatorB:Creator
    {
        public override Product FactoryMothed()
        {
            return new ConcreteProductB();
        }
    }

    情景案例

    以麥當勞的漢堡為例,假設漢堡有兩種牛肉堡和雞肉堡,不同的漢堡有不同的漢堡廚師制作。
    可能有疑問:為是麽是有工廠設計模式呢,反而多個多類更麻煩?
  • 重寫大量重復代碼: 如果創建廚師類需要復雜的過程,比如驗證廚藝水平等等,並不是簡單通過new就能完成,那麽將這些驗證放入工廠會減少重寫大量重復代碼
  • 容易擴展: 如果再家一個芝士堡只需添加芝士堡類與芝士堡廚師類,滿足開閉原則

    public class FactoryApp
    {
        public static void Run()
        {
            BurgerCook[] burgerCook = new BurgerCook[2];
    
            burgerCook[0] = new BeefBurgerCook();
            burgerCook[1] = new ChickenBurgerCook();
    
            foreach (BurgerCook cook in burgerCook)
            {
                Burger burger = cook.MarkBurger();
                Console.WriteLine("Created {0}", burger.GetType().Name);
            }
        }
    }
    
    public class Burger
    { }
    public class BeefBurger : Burger
    { }
    public class ChickenBurger : Burger
    { }
    
    public abstract class BurgerCook
    {
        public abstract Burger MarkBurger();
    }
    
    public class BeefBurgerCook : BurgerCook
    {
        public override Burger MarkBurger()
        {
            return new BeefBurger();
        }
    }
    
    public class ChickenBurgerCook : BurgerCook
    {
        public override Burger MarkBurger()
        {
            return new ChickenBurger();
        }
    }

工廠模式(Factory Method Pattern)