笔记:Gof设计模式--Template Method

1、意图

  Define the skeleton of an algorithm in an operation, deferring somesteps to subclasses. Template Method lets subclasses redefinecertain steps of an algorithm without changing the algorithm'sstructure. 

2、适应性

  The Template Method pattern should be used

  •  to implement the invariant parts of an algorithm once and leave it upto subclasses to implement the behavior that can vary.

  •  when common behavior among subclasses should be factored and localizedin a common class to avoid code duplication. This is a good example of"refactoring to generalize" as described by Opdyke andJohnson [OJ93].
You first identify thedifferences in the existing code and then separate the differencesinto new operations. Finally, you replace the differing code with atemplate method that calls one of these new operations.

  •  to control subclasses extensions. You can define a template methodthat calls "hook" operations (see Consequences) at specific points,thereby permitting extensions only at those points.

3、结构

4、示例代码

  View's DoDisplayhook operation performs the actual drawing. Display callsSetFocus before DoDisplay to set up the drawingstate; Display calls ResetFocus afterwards torelease the drawing state.

void View::Display () { 
 SetFocus(); 
 DoDisplay(); 
 ResetFocus(); 
} 


 

To maintain the invariant, the View's clients always callDisplay, and View subclasses always overrideDoDisplay.

// DoDisplay does nothing in View: 
void View::DoDisplay () { } 

// Subclasses override it to add their specific drawing behavior: 
void MyView::DoDisplay () { 
 // render the view's contents 
} 


 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值