浅尝DesignPattern_Factory

本文通过具体的代码示例,详细解析了工厂模式的实现方法,并探讨了如何通过工厂模式降低类之间的耦合度,使代码更加灵活易扩展。

UML:

2010042020204324.png

-------------------------------------------------------------------------------------------

PARTICIPANTS:

Product  (Page)
  • defines the interface of objects the factory method creates
  • 定义工厂方法创造的对象接口
ConcreteProduct  ()
  • implements the Product interface
  • 实现Product接口
Creator  ()
  • 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对象
ConcreteCreator  ()
  • 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].其实要去盘但是否分离并不难,那就是如果你能够想到多余一个的动机去改变一个类,那么这个累就具有多于一个的职责,就应该考虑类的职责分离.

转载于:https://www.cnblogs.com/TivonStone/archive/2010/04/20/1716558.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值