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
See it run
One object, two halves: the base part keeps the order, the own part fills the gaps.
Operations
Making tea
Follow the order. Blue calls go to the half that has the step.
Step 1 of 7
An order
The barista calls the one public method. They do not say how tea is made.
Step 1: An order
def prepare_recipe(self): self._boil_water() self._brew() self._pour_in_cup() if self._wants_condiments(): self._add_condiments()- Watch
- Who answers
- Result
- Four steps
The own part never calls. It is called.
In the real world
The same template method doing real jobs. Pick one and step through it.
Bread, filling, toppings, wrap.
Step 1 of 3
BLT
Filling: bacon, lettuce, tomato. Toppings: mayonnaise.
Step 1: BLT
Common mistakes
The bugs interviewers watch for, with the fix beside each.
The order can be overridden
criticalOne subclass writes its own order and misses every later rule.
Wrongclass Espresso(BeverageMaker): def prepare_recipe(self): self._brew()Rightclass BeverageMaker(ABC): @final def prepare_recipe(self): ...An open step in the constructor
criticalThe subclass is not built yet.
Wrongdef __init__(self): self.title = self._make_title()Rightdef __init__(self, title): self.title = titlePlease call super
majorSomebody forgets, and nothing complains.
Wrongdef open(self): super().open() # do not forget!Rightdef open(self): # final self._track() self._on_open() # empty hookAn empty body instead of abstract
majorA drink without brewing is served as hot water.
Wrongdef _brew(self): passRight@abstractmethoddef _brew(self): ...Cleanup as the last line
criticalA step that raises skips it.
Wrongrows = self._parse(source)self._close(source)Righttry: rows = self._parse(source)finally: self._close(source)Asking for the class in the skeleton
majorThe base class knows its children.
Wrongif isinstance(self, Coffee): self._ask()Rightif self._wants_condiments(): self._add_condiments()
Interview tips
Find the rows
- Variants side by side.
- Equal: fixed.
- Different: abstract.
- Mostly equal: hook.
Lock what matters
- Template final.
- Fixed steps private.
- Steps protected.
Keep steps innocent
- Arguments in.
- Results out.
- Nothing to remember.
Know the exit
- Two steps vary?
- Inject them.
- Keep the skeleton.