Template method pattern
medium 50 minTemplate 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
Template method
1:02Reel
More reels
One idea each, a minute or less.
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
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.
1988
Ralph Johnson and Brian Foote publish Designing Reusable Classes (June/July, Journal of Object-Oriented Programming). They describe inversion of control in frameworks.
1994
The book Design Patterns names Template Method and lists it among the behavioral patterns.
2005
Martin Fowler describes the Call Super smell on 11 August, with this pattern as the way out.
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.
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 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
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)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
1/3One class
Four steps and an order. Fine.
uses
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
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
| Step | Tea | Coffee | Hot chocolate | Kind |
|---|---|---|---|---|
| boilWater | same | same | same | Fixed |
| brew | Steep 5 minutes | Drip through the filter | Mix in cocoa powder | Abstract |
| pourInCup | same | same | same | Fixed |
| wantsCondiments | yes (default) | Asks the customer | yes (default) | Hook |
| addCondiments | Lemon | Milk and sugar | Cream and marshmallows | Abstract |
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 method | Strategy | |
|---|---|---|
| Varies | Some steps | The whole algorithm |
| By | Inheritance | Composition |
| Chosen | When the object is created. Its class never changes | Any time, can be swapped |
| Who keeps the order | The base class | Each strategy for itself |
| Two independent choices | Subclasses multiply | Two slots |
| Says | Don't call us, we'll call you | Choose your way |
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
Teasees 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.