浅尝DesignPattern_Template

本文深入解析了UML中的模版方法模式,通过定义抽象类和具体类的实现,实现了算法步骤的灵活定制与复用。示例代码展示了如何使用模版方法模式解决算法实现中的通用性和灵活性需求。

UML:

2010042714065427.png

AbstractClass  ()
  • defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm
  • 定义一个抽象的原始操作,来使子类实现算法步骤
  • implements a template method defining the skeleton of an algorithm. The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
  • 实现一个定义了算法节后的模版方法.该模版方法需要原始操作和抽象类中定义的操作.
ConcreteClass  ()
  • implements the primitive operations to carry out subclass-specific steps of the algorithm
  • 实现原始操作,来实现子类的特殊操作

 

1 abstract class AbstractClass
2 {
3 public abstract void PrimitiveOperation1();
4 public abstract void PrimitiveOperation2();
5
6 public void TemplateMethod()
7 {
8 PrimitiveOperation1();
9 PrimitiveOperation2();
10 Console.WriteLine("");
11 }
12 }

 

ContractedBlock.gifExpandedBlockStart.gif代码

 

ContractedBlock.gifExpandedBlockStart.gif代码

 

ContractedBlock.gifExpandedBlockStart.gif代码
1 #region Template
2 AbstractClass aA = new ConcreteClassA();
3 aA.TemplateMethod();
4 AbstractClass aB = new ConcreteClassB();
5 aB.TemplateMethod();
6 #endregion

 

模版方法模式:定义一个操作中的算法股价,而将一些步骤延迟到子类中.模版方法是的子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤.

模版方法模式是通过把不变行为搬移到超类,取出子类中的重复代码来体现它的优势.它提供了一个很好的复用平台.

转载于:https://www.cnblogs.com/TivonStone/archive/2010/04/27/1722076.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值