AlgoViz

Template method pattern

medium 50 min

Template method writes the order of an algorithm once, in a base class, and leaves some steps open for subclasses.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:38

Template method

1:02Reel

More reels

One idea each, a minute or less.

Play all in Bytesized Learning

Strategy vs template method

0:34Reel

Theory

Read or listen first. About 2 min.

What it is

Template method is a behavioral design pattern. A base class has a method with the skeleton of an algorithm. The method calls steps. Some steps are written in the base class, others are left to subclasses.

The pattern works by inheritance and dynamic dispatch: this.brew() in the base class runs the version of the object's own class.

There are three kinds of steps. Fixed steps are the same for all. Abstract steps must be filled. Hooks have a default and may be filled.

Why it exists

It removes copies. Steps that are equal are written once, and a new rule reaches all variants.

It protects the order. A subclass can not skip boiling, pour before brewing, or forget to close a file.

It is the heart of frameworks: the framework owns the flow, and the user fills in steps. Control is inverted.

A short history

  1. 1983

    Richard Sweet writes "Don't call us, we'll call you (Hollywood's Law)" in a paper on Mesa, according to Martin Fowler's note on inversion of control.

  2. 1988

    Ralph Johnson and Brian Foote publish Designing Reusable Classes (June/July, Journal of Object-Oriented Programming). They describe inversion of control in frameworks.

  3. 1994

    The book Design Patterns names Template Method and lists it among the behavioral patterns.

  4. 2005

    Martin Fowler describes the Call Super smell on 11 August, with this pattern as the way out.

  5. 2019

    Python 3.8 gains the final decorator (PEP 591), which lets type checkers protect a template method.

Words to know

Template method
The method that holds the order of steps.
Primitive operation
An abstract step that a subclass must fill.
Hook
A step with a default that a subclass may fill.
Invariant part
What is the same in all variants: the order and the fixed steps.
Hollywood principle
Don't call us, we'll call you. The base class calls the subclass.
Inversion of control
The framework runs the flow and calls your code.
Non-virtual interface
Public functions are not virtual, virtual ones are not public. The C++ form of this idea.
Call super
A smell: an override must remember to call the parent's version.
Fragile base class
A base class whose internal change breaks subclasses.
Skeleton
The fixed frame of an algorithm, with gaps.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

How it works

Step through the idea, or press Play.

Step 1 of 3

Client calls. One public final method

Understand it

Start here

Fixed steps, open inks

Tea and coffee are made in nearly the same way. Boil water, brew, pour, add something. Two steps are equal, two differ, and the order never changes. The pattern on this page writes the order down once and leaves only the differing steps open.

The screen-printing frame

The frame calls for the ink. The ink never calls the frame. That is the whole idea.

Four kinds of methods

  • Template method

    Holds the order: prepareRecipe, mine, runGameLoop, generateDocument. Public, and closed to overriding.

  • Fixed step

    Written once in the base class and the same for all: boilWater, pourInCup. Best private.

  • Abstract step

    Must be filled by each subclass: brew, addCondiments, parse, createContent. Also called primitive operation.

  • Hook

    May be filled. It has a default that is empty or returns a plain answer: wantsCondiments, beforeParsing, onComplete.

A sandwich shop works the same way. Get bread, add filling, add toppings, wrap. A BLT fills in bacon, lettuce and tomato, then mayonnaise. Grilled cheese fills in cheese, then butter. Peanut butter and jelly fills in both and leaves the toppings empty. The shop decides the order, the sandwich decides the filling.

Why

What goes wrong without it

Python
class Tea:    def prepare(self):        return ["boil water", "steep tea", "pour into cup", "add lemon"]class Coffee:    def prepare(self):        return ["boil water", "pour into cup", "drip coffee", "add milk"]# A new rule: rinse the cup before pouring. Somebody edits Tea.class Tea:    def prepare(self):        return ["boil water", "steep tea", "rinse cup", "pour into cup", "add lemon"]for drink in (Tea(), Coffee()):    steps = drink.prepare()    ok = "rinse cup" in steps and steps.index("pour into cup") > 1    print(type(drink).__name__, "ok" if ok else "wrong:", "" if ok else steps)
Run it. Two classes copy one recipe. A rule is added to one of them, and nobody notices.
Edit and run it in your browser

Coffee has two faults. The new rule did not reach it, and its pouring comes before its brewing. No compiler can see either, because the order is written only as a habit.

The design that hurts

Tea- boilWater()- steepTeaBag()- pourInCup()- addLemon()+ prepare(): the order

1/3One class

Four steps and an order. Fine.

uses

The smell: classes that differ in two lines and repeat the other ten.

One skeleton

  • Shared steps written once
  • The order can not be changed by accident
  • A new rule is one line
  • A new drink is two methods

Copied recipes

  • Shared steps written in every class
  • The order is a habit, not a rule
  • A change means editing all classes
  • One forgotten copy is enough

The idea

Turn the call around

Normally your class calls a library. Here the base class calls your class. This is the Hollywood principle: don't call us, we'll call you. It is also named inversion of control, and it is the reason why frameworks are full of this pattern.

The pattern in general

«abstract»AbstractClass+ templateMethod() final- fixedStep()# stepOne() abstract# stepTwo() abstract# hook(): default

1/3The skeleton

One public method with the order. It is final. The steps it calls are protected or private: nobody outside should call them one by one.

usesextends (is a)

One order, two drinks

Tea is one object. The base part and the tea part are two halves of it: the class it inherits from and the class it is.
StepTeaCoffeeHot chocolateKind
boilWatersamesamesameFixed
brewSteep 5 minutesDrip through the filterMix in cocoa powderAbstract
pourInCupsamesamesameFixed
wantsCondimentsyes (default)Asks the customeryes (default)Hook
addCondimentsLemonMilk and sugarCream and marshmallowsAbstract
Fill this table before you write code. Rows that are equal become fixed steps.

Designing steps

Fixed, abstract or hook?

What kind of step is it?

Three shapes of hooks

  • Question

    Returns yes or no and steers the skeleton: wantsCondiments(). Never ask for the type instead.

  • Notification

    Called at a moment, does nothing by default: onComplete(), beforeParsing().

  • Value

    Supplies a part: which table, which timeout, which object. If it returns a new object, it is a factory method.

Espresso needs no pouring step. How do you fit it in?

BreaksOverride the template method
How
Espresso writes its own order.
Limit
Every rule that you add to the skeleton now misses espresso. In Java it does not compile, because the method is final.
Choose when
Never.
WorksA hook around the step
How
needsPouring() returns true by default.
Limit
Each exception adds a hook. After five, the skeleton is a list of ifs.
Choose when
One or two exceptions.
StrongAsk whether it is the same algorithm
How
If brewing into the cup is a second recipe, give it a second skeleton, or pass a list of steps.
Limit
Two things to keep in step.
Choose when
The exceptions touch the order itself.

Neighbours

Template method or Strategy?

Template methodStrategy
VariesSome stepsThe whole algorithm
ByInheritanceComposition
ChosenWhen the object is created. Its class never changesAny time, can be swapped
Who keeps the orderThe base classEach strategy for itself
Two independent choicesSubclasses multiplyTwo slots
SaysDon't call us, we'll call youChoose your way
They combine well. A skeleton may hold strategies for its steps.

Which one?

Choosing

When to use it and when not

Use it when

  • Several classes share the same procedure and differ in a few steps
  • The order must be guaranteed
  • You want to decide exactly what may be changed and what not
  • You build a framework and others fill in steps
  • Setup and cleanup must always happen around the variable part

Leave it when

  • The steps differ completely between variants
  • The behaviour must change while the object lives
  • There is only one implementation
  • It would make a third or fourth level of inheritance
  • Subclasses already extend something else (one parent in Java, C# and others)

What you pay

  • The flow jumps

    A reader of Tea sees two methods and no beginning. They must open the base class to understand when they run.

  • One parent

    The single parent slot is used up for a recipe.

  • The base class is an interface

    Every protected name is a promise to all subclasses. Changing it breaks code that you may never see.

  • Broken substitution

    A step that raises, waits or skips its job breaks the skeleton. See Liskov.

Summary

The whole topic in one minute.

Line up the variants. Equal rows become private fixed steps, different rows abstract steps, optional rows hooks with a safe default. One public final method holds the order.

The base class calls the subclass, never from a constructor, and treats each step as foreign code: cleanup in finally, data through arguments, a written contract.

A base class that others extend is a published interface. Add hooks, not abstract steps. When steps vary independently or at run time, keep the skeleton and inject the steps.

  • Write the order once, in a method that nobody can override.
  • Fixed steps are private, abstract steps must be filled, hooks may be filled.
  • The base class calls the subclass, at the moment it decides.
  • Cleanup belongs to the skeleton, in a finally.
  • Never call an open step from a constructor.
  • Steps that vary independently or at run time: inject them instead.

Sources