[Design Pattern] Template Method Pattern

来源:互联网 发布:js清空tr里的数据 编辑:程序博客网 时间:2024/05/17 21:51

The Template Method Pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

 一. 基本的 Template Method Pattern 示例:

 

二. Template Method Pattern with hook  示例 :

 

三.  Hook 示例:

 

四.  使用 Hook :

 

Template Method Pattern 概要: 

Ø         A "template method" defines the steps of an algorithm, deferring to subclasses for the implementation of those steps.
 
Ø         The Template Method gives up an important technique for code reuse.
 
Ø         The template method's abstract class may define concrete classes, abstract classes and hooks.
 
Ø         Abstract methods are implemented by subclasses.
 
Ø         Hooks are methods that do nothing or default behavior in the abstract classes, but may be overridden in the subclass.
 
Ø         To prevent subclasses from changing the algorithm in the template method, declare the template method as final.
 
Ø         The Hollywood Principle guides us to put decision-making in high-level modules that can decide how and when to call low-level modules.
 
Ø         You'll see lots of uses of the Template Method Pattern in real world code, but don't expect it all (like any pattern) to be designed "by the book".
 
Ø         The strategy and Template Method Patterns both encapsulate algorithms, one by inheritance and one by composition.
 
Ø         The Factory Method pattern is a specialization of Template Method.
 
 

 

摘自 Head First Design Patterns, O' REILLY

原创粉丝点击