工廠方法模式
工廠方法模式(Factory Method):定義一個用於建立物件的介面,讓子類決定例項化哪一個類。工廠方法是一個類的例項化延遲到其子類。
工廠方法模式UML結構圖
工廠方法模式結構程式碼
/// <summary> /// 宣告'Product' 抽象類 /// </summary> abstract class Product { } /// <summary> /// 宣告 'ConcreteProductA' 類,繼承Product /// </summary> class ConcreteProductA : Product { } /// <summary> /// 宣告 'ConcreteProductB 類,繼承Product /// </summary> class ConcreteProductB : Product { } /// <summary> /// 宣告 'Creator' 抽象類 /// </summary> abstract class Creator { //工廠方法 public abstract Product FactoryMethod(); } /// <summary> /// 宣告 'ConcreteCreatorA' 類,繼承Creator類 /// </summary> class ConcreteCreatorA : Creator { //實現父類工廠方法返回類ConcreteProductA例項 public override Product FactoryMethod() { return new ConcreteProductA(); } } /// <summary> /// 宣告 'ConcreteCreatorB' 類,繼承Creator類 /// </summary> class ConcreteCreatorB : Creator { //實現父類工廠方法返回類ConcreteProductB例項 public override Product FactoryMethod() { return new ConcreteProductB(); } } class Program { static void Main(string[] args) { Creator[] creators = new Creator[2]; creators[0] = new ConcreteCreatorA(); creators[1] = new ConcreteCreatorB(); foreach (Creator creator in creators) { Product product = creator.FactoryMethod(); Console.WriteLine("Created {0}",product.GetType().Name); } Console.ReadKey(); } }
執行結果:
工廠模式例項程式碼
/// <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(); } }
執行結果:
簡單工廠模式和工廠方法模式的區別
簡單工廠模式的最大優點在於工廠類中包含了必要的邏輯判斷,根據客戶端的選擇條件動態例項化相關的類,對於客戶端來說,去除了與具體產品的依賴。
工廠方法模式實現時,客戶端需要決定例項化哪一個工廠來實現運算類,選擇判斷的問題還是存在的,也就是說,工廠方法把簡單工廠的內部邏輯判斷移到了客戶端程式碼來進行。如想要加功能,本來是改工廠類的,而現在是修改客戶端。