Card 01/ 09

ConceptDifficulty: Intermediate3 min

Template Method Pattern: Fixing the Steps and Letting Subclasses Fill Them In

Every report is load, format, save; only the format step differs.

The Template Method pattern puts the fixed order of an algorithm's steps in one method of a base class, and leaves some of the steps to subclasses. The base class decides what happens and in what order; each subclass decides how its own steps are done. This card covers the problem that calls for it, the intent, and when it fits.

The problem is a sequence copied into every class. A reporting tool produces sales and stock reports. Each loads its data, formats it, and saves the result, and only the formatting differs. Written as two independent classes, the load and save code is repeated, and a change to the sequence, such as logging each report, has to be made in both and remembered for the next.

A sequence in every class, and a sequence in one place

Without the patterneach report repeats the order

py
class SalesReport:
    def produce(self):
        data = load()
        text = format_sales(data)
        save(text)


class StockReport:
    def produce(self):
        data = load()
        text = format_stock(data)
        save(text)

With the patternthe base class owns the order

py
class Report(ABC):
    def produce(self):
        data = load()
        text = self.format(data)
        save(text)

    @abstractmethod
    def format(self, data): ...

Each report writes only format, and produce exists once.

The Gang of Four state the intent as: define the skeleton of an algorithm in an operation, deferring some steps to subclasses, so that subclasses can redefine certain steps without changing the algorithm's structure. The method that holds the skeleton is the template method.

A recipe is a familiar picture. The order is fixed: make the pastry, add the filling, bake. The cook chooses the filling. The picture breaks on discipline: a cook can skip a step, and in some languages a subclass can do the same by replacing the whole method, which the pattern is meant to prevent.

Template Method is one of eleven behavioural patterns, the family concerned with which object does which part of the work, and how objects communicate.

The behavioural family, with this pattern marked
PatternWhat it does
Chain of ResponsibilityPasses a request along a chain of handlers until one handles it.
CommandTurns a request into an object that can be stored, queued or undone.
InterpreterRepresents a small language's grammar as classes and evaluates its sentences.
IteratorVisits the elements of a collection without exposing how it is stored.
MediatorRoutes the communication between objects through one central object.
MementoCaptures an object's state so it can be restored later.
ObserverNotifies many objects when one object changes.
StateChanges an object's behaviour when its internal state changes.
StrategySwaps one algorithm for another behind a common interface.
Template Method (this topic)Fixes an algorithm's steps in a base class and lets subclasses fill some in.
VisitorAdds operations to a class hierarchy without changing its classes.
Template Method

Use it when

  • Several classes run the same steps in the same order, and differ in one or two of them.
  • The order must be enforced, such as validation always running before storing.
  • A framework must call code the user writes, at points the framework decides.

Avoid it when

  • The varying step should be chosen at run time, which a strategy passed in does without a subclass.
  • Subclasses would override most of the steps, so little of the skeleton is really shared.
  • The class hierarchy is already deep, and another level of inheritance makes it harder to follow.