- Summary
- Define the skeleton of an algorithm in an operation, deferring some steps to subclasses.
- Template Method lets subclasses redefine certain steps of
an algorithm without letting them to change the algorithm's structure.
- When to Use
- When you need to write generic implementation that need to be work with any type or multiple types.
- Example
- Generic shorting mechanism provided by .net collections.
- Overview Tutorials
- http://www.oodesign.com/template-method-pattern.html
- Specific Considerations
- Concrete base class
- It is not necessary to have the superclass as a abstract class. It can be a concrete class containing a method (template method) and some default functionality.
- In this case the primitive methods can not be abstract and this is a flaw because it is not so clear which methods have to be overridden and which not.
- A concrete base class should be used only when customizations hooks are implemented.
- Template method can not be overridden
- The template method implemented by the base class should not be overridden.
- The specific programming language modifiers should be used to ensure this.
- Minimizing primitive methods number
- It's important when designing template methods to minimize the number of primitive methods that a subclass must override in order to provide a clear an easy way to implement concrete templates.
- Naming Convection
- In order to identify the primitive methods is it better to use a specific naming convention. For example the prefix “do” can be used for primitive methods.
- In a similar way the customizations hooks can have prefixes like “pre” and “post”.
- Template Method Vs Strategy Design Pattern
- The strategy and Template Method pattern both achieve same goal with different approaches.
- The difference consists in the fact that Strategy uses delegation while the Template Methods uses the inheritance.
- Template Method and Inverted Control Structure (Hollywood principle)
- Template method is using as an inverted controls structure, sometimes
referred as “the Hollywood principle”:
from the superclass point of view: “Don't
call us, we'll call you” (base will not call derived but derived will call
base).
- This refers to the fact that instead of calling
the methods from base class in the subclasses, the methods from subclass are
called in the template method from superclass.
- Due to the above fact a special care should be
paid to the access modifiers: the
template method should be implemented only in the base class, and the
primitive method should be implemented in the subclasses.
- Templates Hooks
- A particular case of the template method is
represented by the customization hooks.
|
|