LOW-LEVEL DESIGN · BEHAVIORAL PATTERNS · BEHAVIORAL · 39 OF 48

Template Method Pattern in Java: Fixed Steps, Flexible Details

The Template Method pattern in Java with an order fulfilment example: a final method in an abstract class fixes the order of steps, subclasses fill in the steps that differ, and hooks give optional extension points. Covers when to use it, its costs, how it differs from Strategy, where the JDK uses it and how it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 16

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 154 lines, with a small main() demo. Save it as FulfilmentTemplateDemo.java, then run javac FulfilmentTemplateDemo.java && java FulfilmentTemplateDemo.

import java.util.ArrayList;
import java.util.List;

/**
 * Template Method: the base class fixes the order of steps in one final method,
 * subclasses fill in only the steps that differ.
 */
public class FulfilmentTemplateDemo {

    // ---------------------------------------------------------------
    // BEFORE: two copied flows. The grocery copy forgot the payment check.
    // ---------------------------------------------------------------
    static final class RestaurantFlow {
        List<String> run(String orderId) {
            return List.of("verify payment for " + orderId, "cook 2 dishes",
                    "seal in a hot bag", "assign rider");
        }
    }

    static final class GroceryFlow {
        List<String> run(String orderId) {
            // copied from RestaurantFlow, payment check lost on the way
            return List.of("pick 5 items", "pack in paper bags", "assign rider");
        }
    }

    public static void main(String[] args) {
        System.out.println("Before: " + new GroceryFlow().run("G-1"));
        System.out.println("Restaurant copy: " + new RestaurantFlow().run("R-1").size()
                + " steps; the grocery copy lost the payment check");
        System.out.println();

        List<OrderFulfilment> orders = List.of(
                new KitchenFulfilment(2),
                new GroceryFulfilment(5, true),
                new PharmacyFulfilment("RX-310"));

        OrderDesk desk = new OrderDesk();
        String[] ids = {"R-12", "G-77", "P-05"};
        for (int i = 0; i < orders.size(); i++) {
            desk.handle(ids[i], orders.get(i));
        }
    }
}

/** Client: only knows the template method. */
final class OrderDesk {
    void handle(String orderId, OrderFulfilment fulfilment) {
        List<String> steps = fulfilment.fulfil(orderId);
        System.out.println(fulfilment.getClass().getSimpleName() + " " + orderId + ":");
        for (int i = 0; i < steps.size(); i++) {
            System.out.println("  " + (i + 1) + ". " + steps.get(i));
        }
    }
}

/** Abstract class: holds the skeleton. */
abstract class OrderFulfilment {

    /** The template method. Final, so no subclass can skip or reorder steps. */
    public final List<String> fulfil(String orderId) {
        List<String> log = new ArrayList<>();
        log.add("verify payment for " + orderId);   // fixed step, written once
        log.add(prepareItems());                     // abstract step
        log.add(packItems());                        // abstract step
        if (needsColdBox()) {                        // hook
            log.add("add ice packs");
        }
        log.add("assign rider");                     // fixed step, written once
        log.addAll(afterDispatch(orderId));          // hook
        return log;
    }

    /** Steps every subclass must provide. Protected: callers cannot run them alone. */
    protected abstract String prepareItems();

    protected abstract String packItems();

    /** Hook with a safe default. */
    protected boolean needsColdBox() {
        return false;
    }

    /** Hook with a do-nothing default. */
    protected List<String> afterDispatch(String orderId) {
        return List.of();
    }
}

final class KitchenFulfilment extends OrderFulfilment {
    private final int dishes;

    KitchenFulfilment(int dishes) {
        this.dishes = dishes;
    }

    @Override
    protected String prepareItems() {
        return "cook " + dishes + " dishes";
    }

    @Override
    protected String packItems() {
        return "seal in a hot bag";
    }
}

final class GroceryFulfilment extends OrderFulfilment {
    private final int items;
    private final boolean hasFrozenItems;

    GroceryFulfilment(int items, boolean hasFrozenItems) {
        this.items = items;
        this.hasFrozenItems = hasFrozenItems;
    }

    @Override
    protected String prepareItems() {
        return "pick " + items + " items from shelves";
    }

    @Override
    protected String packItems() {
        return "pack in paper bags";
    }

    @Override
    protected boolean needsColdBox() {
        return hasFrozenItems;
    }
}

final class PharmacyFulfilment extends OrderFulfilment {
    private final String prescriptionId;

    PharmacyFulfilment(String prescriptionId) {
        this.prescriptionId = prescriptionId;
    }

    @Override
    protected String prepareItems() {
        return "pharmacist checks prescription " + prescriptionId;
    }

    @Override
    protected String packItems() {
        return "seal in a tamper-proof pouch";
    }

    @Override
    protected List<String> afterDispatch(String orderId) {
        return List.of("send prescription receipt for " + orderId);
    }
}

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.

Copied flows
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.

Template method
  • 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.

OrderFulfilment.fulfil()
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.

A concrete subclass
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.

Hooks
// 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.

Control is inverted
  • 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.

Good fit
  • 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.

Costs
  • 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 vs Strategy
  • 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.

Seen in Java
  • 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.

Where it shows up
  • 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.

Avoid these
  • 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

Interview questions

What is the Template Method pattern?

A base class defines the skeleton of an algorithm in one method and calls abstract or overridable steps from it. Subclasses provide those steps but cannot change the overall order, so the shared parts are written once.

Why should the template method be final?

Making it final stops a subclass from overriding the whole flow and skipping or reordering required steps, such as a validation or payment check. Subclasses can only change the steps they were meant to change.

What is a hook method?

A hook is a step with a default implementation in the base class, often empty or returning false. Subclasses may override it to add optional behaviour, but they do not have to, unlike an abstract step.

How is Template Method different from Strategy?

Template Method varies parts of an algorithm through inheritance and the choice is fixed at compile time. Strategy puts a whole behaviour behind an interface and injects it through composition, so it can be swapped at runtime and combined freely.

Where is Template Method used in the Java standard library?

AbstractList builds many List methods on top of the get and size methods you implement, and InputStream builds its bulk read on top of the single-byte read method. HttpServlet.service also dispatches to doGet and doPost, which subclasses override.

What are the drawbacks of Template Method?

It relies on inheritance, so subclasses are tightly tied to the base class and a change there affects all of them. Steps cannot be swapped at runtime, and when several steps vary independently the number of subclasses grows quickly.

Should the abstract steps be public?

Usually no. They should be protected so that only subclasses implement them and callers can only run the full template method. Public steps let callers run them out of order and break the guarantees of the flow.

How would you use Template Method in a vending machine design?

A base class can fix the purchase flow: select item, collect payment, dispense, return change. Subclasses or variants override only the steps that differ, such as how a coin or card payment is collected, while the order stays fixed.