Sometimes a class will use several different Strategy patterns. When I first looked at the class diagram for the Template Method, I thought, “Oh, the Template Method is simply a collection of Strategies that work together.” This is dangerous (and usually incorrect) thinking. While it is not uncommon for several Strategies to appear to be connected to each other, designing for this can lead to inflexibility.
The Template Method is applicable when there are different, but conceptually similar processes. The variations for each process are coupled together because they are associated with a particular process. In the example I presented, when I need a format a CONNECT command for an Oracle database, if I need a format a QUERY command, it'll be for an Oracle database as well.
The Template Method Pattern: Key Features
Intent
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Redefine the steps in an algorithm without changing the algorithm's structure.
Problem
There is a procedure or set of steps to follow that is consistent at one level of detail, but individual steps may have different implementations at a lower level of detail.
Solution
Allows for definition of substeps that vary while maintaining a consistent basic process.
Participants and Collaborators
The Template Method consists of an abstract class that defines the basic TemplateMethod (see figure below) classes that need to be overridden. Each concrete class derived from the abstract class implements a new method for the Template.
Consequences
Templates provide a good platform for code reuse. They also are helpful in ensuring the required steps are implemented. They bind the overridden steps together for each Concrete class, and so should only be used when these variations always and only occur together.
Implementation
Create an abstract class that implements a procedure using abstract methods. These abstract methods must be implemented in subclasses to perform each step of the procedure. If the steps vary independently, each step may be implemented with a Strategy pattern.
GoF Reference
Pages 325–330.
Figure 18-2. Standard, simplified view of the Template Method pattern.