UML:
-------------------------------------------------------------------------------------------
PARTICIPANTS:
- defines the interface of objects the factory method creates
- 定义工厂方法创造的对象接口
- implements the Product interface
- 实现Product接口
- declares the factory method, which returns an object of type Product. Creator may also define a default implementation of the factory method that returns a default ConcreteProduct object.
- 定义(返回Product类型的对象)的工厂方法,Creator也可以定义一个对(返回一个ConcreteProduct对象)工厂方法的默认实现.
- may call the factory method to create a Product object.
- 也可以调用工厂方法去创建一个Product对象
- overrides the factory method to return an instance of a ConcreteProduct.
- 重写工厂方法来返回一个ConcreteProduct实例
-------------------------------------------------------------------------------------------
SAMPLE:
Operation.cs
1 class Operation
2 {
3 public double numberA { get; set; }
4 public double numberB { get; set; }
5 public virtual double getResult()
6 {
7 double result = 0;
8 return result;
9 }
10 }
OperationAdd.cs
1 class OperationAdd:Operation
2 {
3 public override double getResult()
4 {
5 double result = 0;
6 result = base.numberA + base.numberB;
7 return result;
8 }
9 }
OperationSub.cs
1 class OperationSub : Operation
2 {
3 public override double getResult()
4 {
5 double result = 0;
6 result = base.numberA - base.numberB;
7 return result;
8 }
9 }
1 class OperationMul : Operation
2 {
3 public override double getResult()
4 {
5 double result = 0;
6 result = base.numberA * base.numberB;
7 return result;
8 }
9 }
OperationDiv.cs
1 class OperationDiv : Operation
2 {
3 public override double getResult()
4 {
5 double result = 0;
6 if (numberB == 0)
7 throw new Exception("0 is not available");
8 result = base.numberA / base.numberB;
9 return result;
10 }
11 }
OperationFactory.cs
1 class OperationFactory
2 {
3 public static Operation creatOperation(string operateMethod)
4 {
5 Operation operation = null;
6 switch (operateMethod)
7 {
8 case "+":
9 operation = new OperationAdd();
10 break;
11 case "-":
12 operation = new OperationSub();
13 break;
14 case "*":
15 operation = new OperationMul();
16 break;
17 case "/":
18 operation = new OperationDiv();
19 break;
20 }
21 return operation;
22 }
23 }
①如果一个类承担的责任过多,就等于把这些职责耦合到一起,一个职责的变化可能会削弱或者一直这个类完成其他职责的能力.这种耦合会导致脆弱的设计,当变化发生时,设计会遭受到意想不到的破坏[ASD].
②软件设计真正要做的许多内容,就是发现职责并把那些职责相互分离[ASD].其实要去盘但是否分离并不难,那就是如果你能够想到多余一个的动机去改变一个类,那么这个累就具有多于一个的职责,就应该考虑类的职责分离.