Card 02/ 09

ConceptDifficulty: Intermediate1 min

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.

Template Method participants
Each method and who defines it
MethodKindDefined byA subclass
templateMethodTemplate methodThe abstract classMust not override it
stepOne, stepTwoAbstract step, also called a primitive operationDeclared by the abstract class, written by each subclassMust write it
hookHookThe abstract class, with a default that usually does nothingMay 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.