工厂方法模式

---恢复内容开始---

工厂方法模式

  定义:定义一个用于创建对象的接口,让子类决定实例化哪个类。工厂方法使一个类的实例化延迟到其子类。

  

  在这之前学习了简单工厂模式,用简单工厂模式实现了计算器功能。

  工厂类代码如下:

 1     public class OperationFactory
 2     {
 3         public static Operation CreateOperae(string operate)
 4         {
 5             Operation oper = null;
 6             switch (operate)
 7             {
 8                 case "+":
 9                     oper = new OperationAdd();
10                     break;
11                 case "-":
12                     oper = new OperationSub();
13                     break;
14                 case "*":
15                     oper = new OperationMul();
16                     break;
17                 case "/":
18                     oper = new OperationDiv();
19                     break;
20             }
21             return oper;
22         }
23     }

  客户端代码:

1             Operation oper;
2             oper = OperationFactory.CreateOperae("+");
3             oper.NumberA = 2;
4             oper.NumberB = 5;
5             double result = oper.GetResult();            

 

  工厂模式实现:

1     /// <summary>
2     /// 工厂接口
3     /// </summary>
4     interface IFactory
5     {
6         Operation CreateOperation();
7     }

  构建具体的工厂去实现这个接口

 1     class AddFactory : IFactory
 2     {
 3         public Operation CreateOperation()
 4         {
 5             return new OperationAdd();
 6         }
 7     }
 8 
 9     class SubFactory : IFactory
10     {
11         public Operation CreateOperation()
12         {
13             return new OperationSub();
14         }
15     }
16 
17     class MulFactory : IFactory
18     {
19         public Operation CreateOperation()
20         {
21             return new OperationMul();
22         }
23     }
24 
25     class DivFactory : IFactory
26     {
27         public Operation CreateOperation()
28         {
29             return new OperationDiv();
30         }
31     }

  客户端代码:

1             IFactory operFactory = new AddFactory();
2             Operation oper = operFactory.CreateOperation();
3             oper.NumberA = 1;
4             oper.NumberB = 2;
5             double result = oper.GetResult();    

 

  简单工厂模式的最大优点在于工厂类中包含了必要的逻辑判断,根据客户端的选择条件动态实例化相关的类,对于客户端来说,去除了与具体产品的依赖。

  但是新增一个运算功能时,我们需要给运算工厂类的方法里面增加一个“case”分支条件,这样违背了  开放—封闭原则

  工厂方法模式实现时,客户端需要解决实例化哪一个工厂来实现运算类,选择判断的问题还是存在的,也就是说,工厂方法把简单工厂内部逻辑判断移到了客户端代码来进行。

  你想要家功能,本来是该工厂类的,而现在是修改客户端。

---恢复内容结束---

posted on 2017-07-11 23:24  zda123000  阅读(216)  评论(0编辑  收藏  举报