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、结构
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
}