工廠方法模式是對簡單工廠模式的改進,它為每個對象增加了一個工廠類,專門用於生成該對象。 工廠方法實現加減乘除例子如下: 1 操作類 2 為每一個操作類添加一個工廠對象 3 在客戶端使用工廠生產需要使用的對象 運行結果為:3 工廠方法模式把判斷移到了客戶端,並沒有解決判斷實例化哪個對象的問題,但這種模 ...
工廠方法模式是對簡單工廠模式的改進,它為每個對象增加了一個工廠類,專門用於生成該對象。
工廠方法實現加減乘除例子如下:
1 操作類
public class Operation { public double NumberA { get; set; } public double NumberB { get; set; } public virtual double GetResult() { double result = 0; return result; } } public class OperationAdd : Operation { public override double GetResult() { return NumberA + NumberB; } } public class OperationSub : Operation { public override double GetResult() { return NumberA - NumberB; } } public class OperationMul : Operation { public override double GetResult() { return NumberA * NumberB; } } public class OperationDiv : Operation { public override double GetResult() { if (NumberB == 0) { throw new Exception("除數不能為0"); } return NumberA / NumberB; } }
2 為每一個操作類添加一個工廠對象
/// <summary> /// 工廠方法模式把簡單工廠的內部邏輯判斷移導了客戶端代碼來進行,增加方法時,不需要增加條件分支,只需增加對象和工廠 /// </summary> interface IFactory { Operation CreateOperation(); } public class AddFactory:IFactory { public Operation CreateOperation() { return new OperationAdd(); } } public class SubFactory : IFactory { public Operation CreateOperation() { return new OperationSub(); } } public class MulFactory : IFactory { public Operation CreateOperation() { return new OperationMul(); } } public class DivFactory : IFactory { public Operation CreateOperation() { return new OperationDiv(); } }
3 在客戶端使用工廠生產需要使用的對象
IFactory addFactory = new AddFactory(); Operation operation = addFactory.CreateOperation(); operation.NumberA = 1; operation.NumberB = 2; Console.WriteLine(operation.GetResult());
運行結果為:3
工廠方法模式把判斷移到了客戶端,並沒有解決判斷實例化哪個對象的問題,但這種模式在某些場景中是有很大的好處的,例如使用SQLServer資料庫,代碼開發完成後,如果數據改為Oracle,只需修改實例化工廠,不需要修改其它地方,更不需要修改被操作對象的實例化過程,下麵比較使用工廠方法模式和不使用時代碼的區別:
private void UseFactory() { //如果所有加法變減法,只修改一句 IFactory addFactory = new AddFactory(); Operation operation1 = addFactory.CreateOperation(); operation1.NumberA = 1; operation1.NumberB = 2; Console.WriteLine(operation1.GetResult()); Operation operation2 = addFactory.CreateOperation(); operation2.NumberA = 5; operation2.NumberB = 3; Console.WriteLine(operation1.GetResult()); Operation operation3 = addFactory.CreateOperation(); operation3.NumberA = 6; operation3.NumberB = 1; Console.WriteLine(operation1.GetResult()); } private void unUseFactory() { //如果所有加法變減法,需要修改所有實例化的地方,簡單工廠也存在該問題 Operation operation1 = new OperationAdd(); operation1.NumberA = 1; operation1.NumberB = 2; Console.WriteLine(operation1.GetResult()); Operation operation2 = new OperationAdd(); operation2.NumberA = 5; operation2.NumberB = 3; Console.WriteLine(operation1.GetResult()); Operation operation3 = new OperationAdd(); operation3.NumberA = 6; operation3.NumberB = 1; Console.WriteLine(operation1.GetResult()); }
總體而言,工廠發放剋服了簡單工廠違反開放-封閉原則的缺點,又保持了封裝對象創建過程的優點,封裝對象創建的過程使得更換對象時,程式不需要做大的改動,降低了客戶端與具體對象的耦合度。