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

工廠方法模式(Factory Method)

method 客戶端代碼 console 實例化 turn 簡單工廠 actor () blog

工廠方法模式:定義一個用於創建對象的接口,讓子類來決定實例化哪一個類。工廠方法使一個類的實例化延遲到子類。

簡單工廠模式的最大有點在於工廠勒種包含了必要的邏輯判斷,根據客戶端的選擇條件動態實例化相關的類,對客戶端來說,去除了與具體產品的依賴。

工廠方法模式實現時,客戶端需要決定實例化哪一個工廠來實現運算類,選擇判斷的問題還是存在的。工廠方法吧簡單工廠的內部邏輯轉移到了客戶端代碼來進行。

/// <summary>
    /// 運算類
    /// </summary>
   public class Operation
    {
        public double
NumA { get; set; } public double NumB { get; set; } public virtual double GetResult() { double result = 0; return result; } } /// <summary> /// 加法類 /// </summary> public class OperationAdd : Operation { public
override double GetResult() { double result = 0; result = NumA + NumB; return result; } } /// <summary> /// 減法類 /// </summary> public class OperationSub : Operation { public override double GetResult() {
double result = 0; result = NumA - NumB; return result; } } /// <summary> /// 工廠接口 /// </summary> public interface IFactory { Operation FactoryMethod(); } /// <summary> /// 加法工廠 /// </summary> public class AddFactory : IFactory { public Operation FactoryMethod() { return new OperationAdd(); } } /// <summary> /// 減法工廠 /// </summary> public class SubFactory : IFactory { public Operation FactoryMethod() { return new OperationSub(); } } class Program { static void Main(string[] args) { IFactory[] fac = new IFactory[2]; fac[0] = new AddFactory(); fac[1] = new SubFactory(); Operation oper; oper = fac[0].FactoryMethod(); oper.NumA=10; oper.NumB=5; Console.WriteLine("Called By {0}", oper.GetType().Name); Console.WriteLine("Result={0}", oper.GetResult().ToString()); oper = fac[1].FactoryMethod(); oper.NumA = 10; oper.NumB = 5; Console.WriteLine("Called By {0}", oper.GetType().Name); Console.WriteLine("Result={0}", oper.GetResult().ToString()); Console.ReadKey(); } }

http://www.cnblogs.com/lxblog/p/4119426.html

工廠方法模式(Factory Method)