Template Method Pattern
Overview
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
changing the algorithm's structure.
Participants
- defines abstract primitive operations that concrete subclasses define to implement steps
of an algorithm.
- 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.
- implements the primitive operations to carry out subclass-specific steps of
the algorithm.
Parameters
- list of names to be used when generating the primitive methods.
-
when selected, will create special JavaDoc links in the code between pattern participants, describing
their relationships.
Applicability
The Template Method pattern should be used
- to implement the invariant parts of an algorithm once and leave it up to subclasses
to implement that behavior that can vary.
- when common behavior among subclasses should be refactored and localized in a common
class to avoid code duplication. You first identify the differences in the existing code
and then separate the differences into new operations. Finally, you replace the differing
code with a template method that calls one of these new operations.
- to control subclasses extensions. You can define a template method that calls "hook"
operations at specific points, thereby permitting extensions only at those points.