Card 02/ 09
Template Method Pattern Structure: The Class Diagram
An AbstractClass with one template method and the primitive steps it calls, and ConcreteClasses that supply them.
Template Method has two participants: an abstract class that holds the template method and declares the steps, and the concrete classes that supply them. This card reads their roles off the Gang of Four's class diagram, then separates the three kinds of method the abstract class contains, because which kind a method is decides whether a subclass must, may, or must not override it.
| Method | Kind | Defined by | A subclass |
|---|---|---|---|
templateMethod | Template method | The abstract class | Must not override it |
stepOne, stepTwo | Abstract step, also called a primitive operation | Declared by the abstract class, written by each subclass | Must write it |
hook | Hook | The abstract class, with a default that usually does nothing | May override it |
The asterisk marks an abstract method, and # marks a protected one: the steps are meant to be called by the template method, not by clients. Clients call only templateMethod.
A hook is a step with a default, which gives a subclass a place to add behaviour without being forced to. A common hook is a check that returns True by default, such as whether to validate a row, so most subclasses ignore it and one can change it.
The control runs in an unusual direction. Normally a subclass calls its parent's methods; here the parent's template method calls the subclass's steps. This is sometimes called the Hollywood principle, "do not call us, we will call you", and it is how most frameworks run your code.
← → move through sections and cards