Notes
The problem
Here is the naive version. Restaurant flow and grocery flow each have their own run method. They look almost the same, so they were copied. Later someone added the payment check to the restaurant flow and forgot the grocery flow. Now grocery orders can ship unpaid. Every rule that should apply to all orders must be added in every copy, and a test for one copy proves nothing about the others.
class RestaurantFlow {
void run(String id) {
checkPayment(id); cook(); bag();
assignRider(id); } }
class GroceryFlow {
void run(String id) {
pick(); bag(); chill();
assignRider(id); } }
// payment check forgotten here The idea
The idea in one sentence: put the skeleton of an algorithm in one method of a base class, and let subclasses supply only the steps that vary. That method is called the template method. Some steps are fixed and written once in the base class. Some are abstract, so every subclass must provide them. And some are hooks, optional steps with a safe default that a subclass may override.
- one method in a base class
- lists the steps in order
- some steps are fixed:
- written once in the base
- some steps are abstract:
- each subclass fills them
- some steps are hooks:
- optional, safe default
- the order itself never moves
Participants
Here are the participants with our names. Order fulfilment is the abstract class. It holds the template method, called fulfil. Kitchen fulfilment, grocery fulfilment and pharmacy fulfilment are the concrete classes. Each extends the base and fills in its own steps. The order desk is the client. It only ever calls fulfil, and it does not care which subclass it is holding.
The template method
This is the template method. It is public and final. Final matters: no subclass can override it, so no subclass can skip the payment check or swap the order of steps. Verifying payment and assigning a rider are written once, right here. Prepare items and pack items are calls to abstract methods. Needs cold box and after dispatch are hooks. The method reads like a checklist.
public final List<String> fulfil(String id){
List<String> log = new ArrayList<>();
log.add("verify payment for " + id);
log.add(prepareItems());
log.add(packItems());
if (needsColdBox()) log.add("ice packs");
log.add("assign rider");
log.addAll(afterDispatch(id));
return log;
} Filling the steps
The abstract steps are protected. They are meant for subclasses, not for callers, so the order desk cannot call prepare items directly. Kitchen fulfilment overrides the two abstract steps: cook the dishes, then seal them in a hot bag. That is the whole class. It has no idea about payments or riders. Adding a new order type means writing two small methods, not copying a flow.
abstract class OrderFulfilment {
protected abstract String prepareItems();
protected abstract String packItems();
}
class KitchenFulfilment
extends OrderFulfilment {
@Override protected String prepareItems()
{ return "cook " + dishes + " dishes"; }
@Override protected String packItems()
{ return "seal in a hot bag"; }
} Hooks
Hooks are steps with a default that usually does nothing. Needs cold box returns false in the base class. Grocery fulfilment overrides it to return true when the basket has frozen items, and the template then adds ice packs. After dispatch returns an empty list by default. Pharmacy fulfilment overrides it to send a prescription receipt. Restaurant orders ignore both hooks completely.
// in OrderFulfilment
protected boolean needsColdBox()
{ return false; }
protected List<String>
afterDispatch(String id)
{ return List.of(); }
// GroceryFulfilment
@Override protected boolean needsColdBox()
{ return hasFrozenItems; } One run
Follow one grocery order. The desk calls fulfil with order G seventy seven. The base class code runs first and logs the payment check. Then it calls prepare items, which runs the grocery version: pick items from shelves. Then pack items, then the cold box hook, which says yes. The base class adds ice packs, assigns a rider and returns five logged steps. It is one object, but control keeps jumping from parent code to child code.
Who is in charge
Notice who is in charge. Normally your code calls a library. Here it is the other way round. The base class runs the show and calls your small methods when their turn comes. This is a simple form of inversion of control, and frameworks use it a lot. The benefit is that a subclass cannot break the sequence. It can only change what happens inside its own slots.
- normal code: you call the
- library when you need it
- template method: the base
- class calls YOUR steps
- when it is their turn
- subclasses stay small and
- cannot break the sequence
When to use it
Use it when several classes follow the same steps in the same order and only a few steps differ. It shines when the order is a rule, like always validating before saving, or always checking payment before shipping. Typical cases are report exports, data import jobs, settlement batches and turn based games. You get one place to fix shared bugs and one place to add a shared step.
- several classes share a flow
- the order of steps must not
- change (rules, audit, safety)
- only a few steps differ
- you want one place to fix
- a bug in the shared part
- examples: report export,
- data import jobs, payment
- settlement, game turns
When not to
It has real costs. It is built on inheritance, so a class can only have one such parent, and the choice is made at compile time. You cannot swap one step at runtime. A change in the base class reaches every subclass. Too many hooks make the flow hard to follow. And if two steps vary independently, say three packing styles times four preparing styles, you end up with twelve subclasses.
- uses inheritance: one parent
- only, chosen at compile time
- cannot swap a step at runtime
- base class changes ripple
- into every subclass
- too many hooks: nobody knows
- what the flow really does
- two varying steps that mix
- freely: subclass explosion
Versus Strategy
Compare it with Strategy. Template method uses inheritance: the subclass is a kind of fulfilment and fills in parts of one algorithm, fixed when the class is written. Strategy uses composition: the fulfilment has a packing style object, passed in, and you can swap it at runtime. A common fix for subclass explosion is to keep the template for the fixed order but turn one varying step into a strategy field.
- template method:
- inheritance, is-a
- varies part of an algorithm
- fixed when the class is made
- strategy:
- composition, has-a
- swaps a whole behaviour
- can change at runtime
- mix: pass a PackingStyle in
In Java
You already use this in Java. Abstract list asks you for just get and size, and builds index of, the iterator, equals and many other methods on top of them. Input stream asks you for one method that reads a single byte, and its bulk read method is written in terms of it. In the servlet API, the service method of http servlet looks at the request method and calls do get or do post, which you override.
- java.util.AbstractList:
- you write get() and size(),
- it builds indexOf, iterator,
- equals and more on top
- java.io.InputStream:
- you write read() of one byte,
- bulk read(byte[], off, len)
- is built from it
- HttpServlet.service():
- calls doGet, doPost, ...
In LLD interviews
In interviews, look for a fixed sequence with a few varying steps. A vending machine always selects, takes payment, dispenses and gives change. A board game framework runs the same turn loop while each game defines its moves. A payment flow validates, charges, records and notifies, with a different charge step per method. Exporters fetch, format and write. Say the word final when you describe it.
- vending machine: select, pay,
- dispense, give change
- board games: one turn loop,
- game-specific moves
- payment flow: validate,
- charge, record, notify
- report or file export:
- fetch, format, write
- parsers: open, read, close
Common mistakes
Common mistakes. Forgetting to make the template method final, so a subclass overrides it and quietly skips a step. Making the steps public, so callers run them out of order. Having a step call back into the template, which loops forever. And adding a hook for every line until nobody can tell what the flow does. Keep the template final, the steps protected and the hooks few.
- template method not final:
- a subclass rewrites the flow
- steps left public:
- callers run them out of order
- subclass calls super step
- that calls the template:
- endless recursion
- a hook for every line
- heavy logic in the base class