Applied Design Patterns with Java
Behavioral :: Template Method (325) {C ch 25}
Applicability
Use the Template
Method pattern in either of the following cases:
- to implement the invariant parts of an algorithm once
and leave it up to subclasses to implement the behavior that can vary.
- when common behavior among subclasses should be factored
and localized in a common class to avoid code duplication. This is a good example of "refactoring to generalize".
First identify the differences in the existing code and then separate the differences into new operations. Finally,
replace the differing code with a Template Method that calls one of these new operations.
- to control subclasses extensions. Define a Template Method
that calls "hook" operations at specific points, permitting extensions only at those points.
Structure
Participants
- AbstractClass (Application) defines
abstract primitive operations that concrete subclasses define to implement steps of an algorithm, and
implements a Template Method defining the skeleton of an algorithm. The Template Method calls primitive
operations as well as operations defined in AbstractClass or those of other objects.
- ConcreteClass (MyApplication) implements the primitive operations to carry out subclass-specific steps
of the algorithm.
Catalog Behavioral Prev Next