Java Reference
In-Depth Information
This pattern is called Template Method because it provides a method that contains the structure of the operation,
but leaves some of the steps open by calling abstract methods. It is like a template, since the subclasses fill in the
blanks by providing implementations for the abstract methods.
Implementation
Figure 2.16 shows the class diagram for the Template Method pattern.
Figure 2.16. Template Method class diagram
Implementing the Template Method requires:
AbstractClass - The AbstractClass is (perhaps not surprisingly) an abstract class that contains the template
method and defines one or more abstract methods. The template method contains the skeletal code and calls one
or more of the abstract methods. To prevent subclasses from overriding the template method it should be declared
final.
ConcreteClass - The ConcreteClass extends the AbstractClass and implements the abstract methods of the
AbstractClass . It relies on the AbstractClass to provide the structure of the operation contained in the
template method.
Benefits and Drawbacks
The main benefit of the Template Method pattern is that it promotes code reuse. Without the Template Method,
code is duplicated in many subclasses. This benefit makes the Template Method essential for frameworks. A
framework contains many methods that only minimally rely on specific implementations in the subclass. Using
the Template Method pattern means the entire structure can be provided by the framework. If you use this
framework, you only have to override a few methods to be able to use it.
If the template method calls too many abstract methods, you'll soon get tired of using the AbstractClass as a
superclass. It is better to have the template method call a limited number of abstract methods.
Pattern Variants
One variant is to have the Template Method call concrete methods instead of abstract methods. The
AbstractClass provides a default implementation for each of the methods called by the Template Method.
These methods are called hook methods.
The rationale is that when you use the AbstractClass , you don't have to override all the methods to be able to
use the Template Method. The AbstractClass might not even need to be abstract.
One responsibility the provider of the Template Method has is to document which methods are used in other
template methods. In the normal Template Method pattern, it is clear which methods need to be overridden,
because all these methods are abstract. If the hook methods are not mentioned in the documentation, they cannot
be identified as such.
Related Patterns
Related patterns include the following:
 
Search WWH ::




Custom Search