Patterns for behaviour · Chapter 19

Template Method pattern

Fix the order of an algorithm's steps in a base class and let subclasses fill in only the steps that differ. Hooks, full Java and Python code, and when Strategy is the better choice.

IntermediateInterview priority: Medium45 min
On this page
  1. The problem: two importers, one copied recipe
  2. The idea: the base class owns the recipe
  3. Build it step by step
  4. Template Method versus Strategy: inheritance versus composition
  5. Other look-alikes
  6. When not to use it
  7. Where you meet it in real code
  8. In the interview
  9. Quiz

The problem: two importers, one copied recipe

A company imports customer lists from partners. The first partner sends CSV, the second sends key=value lines. Both importers do the same five things: read the text, parse it into rows, drop invalid rows, save the rest, and report. Only parse really differs. Written as two independent classes, it looks like this:

class CsvImporter {
    int importText(String text) {
        List<Map<String, String>> rows = parseCsv(text);
        List<Map<String, String>> good = new ArrayList<>();
        for (var row : rows) if (isValid(row)) good.add(row);   // copied
        db.addAll(good);                                        // copied
        return good.size();
    }
}
class KeyValueImporter {
    int importText(String text) {
        List<Map<String, String>> rows = parseKeyValue(text);
        List<Map<String, String>> good = new ArrayList<>();
        for (var row : rows) if (isValid(row)) good.add(row);   // copied
        db.addAll(good);                                        // copied, and someone forgot audit logging here
        return good.size();
    }
}

Every fix to validation or saving must be made twice, and the third partner's importer will copy it a third time. Worse, nothing guarantees the order: one copy might save before validating.

The same steps, copied into two classes

  1. Making tea and making coffee follow the same recipe: boil water, brew, pour into a cup, add extras. Only two steps differ: what you brew, and what you add. Written as two separate classes, the shared steps get copied twice.

The idea: the base class owns the recipe

The Template Method pattern puts the algorithm's skeleton in a base class. One method, the template method, calls the steps in a fixed order. Steps that are the same for everyone are implemented in the base class. Steps that differ are abstract: declared in the base class, with no body, for each subclass to fill in.

The recipe lives in the base class and calls down into the subclass

  1. The template method pattern puts the recipe in a base class. The method prepare() lists the steps in order, and is final, so nobody can change the order. The steps that vary are left abstract, for subclasses to fill in.
  2. When you call prepare() on a Coffee, the base class runs the recipe and calls down into Coffee for the two blanks. The base class calls you; you don’t call it. That’s nicknamed the Hollywood principle: “don’t call us, we’ll call you”.

The control flow is inverted compared with ordinary inheritance: you don't call the base class, the base class calls you. That is the Hollywood principle: "don't call us, we'll call you".

RoleIn this exampleResponsibility
Abstract classDataImporterHolds the template method importText() and the fixed steps
Template methodimportText()Calls the steps in order; final so subclasses can't change the order
Primitive operations (abstract steps)parse()Must be implemented by every subclass
HooksisValid(), afterImport()Optional steps with a default; subclasses override only if they care
Concrete classesCsvImporter, KeyValueImporterFill in the abstract steps and override the hooks they need

Build it step by step

1. The template method. importText() lists the steps. In Java it is final. In Python, @typing.final is only a hint for type checkers such as mypy; the language itself won't stop an override, so say so in a docstring too.

2. Abstract steps. parse() has no default, so a new importer that forgets it fails at once: a compile error in Java, a TypeError on construction in Python (because of ABC and @abstractmethod).

3. Hooks. isValid() has a sensible default that a stricter importer can extend with super. afterImport() does nothing by default; one importer uses it to notify an admin.

4. The client creates the importer it needs and calls the template method.

import java.util.*;

// ---------- Client ----------
public class ImportDemo {
    public static void main(String[] args) {
        List<Map<String, String>> db = new ArrayList<>();
        String csv = "name,email\nAna,ana@example.com\nBo,\nCy,cy@example.com";
        String kv  = "name=Dee;email=dee@example.com\nname=Eli;email=not-an-email";

        new CsvImporter(db).importText(csv);
        new KeyValueImporter(db).importText(kv);
        System.out.println("saved: " + db.size() + " rows");
    }
}

// ---------- The base class owns the recipe ----------
abstract class DataImporter {
    private final List<Map<String, String>> db;
    protected DataImporter(List<Map<String, String>> db) { this.db = db; }

    /** The template method: final, so no subclass can reorder or skip steps. */
    public final int importText(String text) {
        List<Map<String, String>> rows = parse(text);           // 1. varies: abstract
        List<Map<String, String>> good = new ArrayList<>();
        for (Map<String, String> row : rows) {                  // 2. fixed, with a hook inside
            if (isValid(row)) good.add(row);
            else System.out.println("  " + name() + " skipped " + row);
        }
        db.addAll(good);                                        // 3. fixed
        afterImport(good.size());                               // 4. hook: does nothing by default
        return good.size();
    }

    protected abstract List<Map<String, String>> parse(String text);

    /** Hook with a sensible default; subclasses may tighten it. */
    protected boolean isValid(Map<String, String> row) {
        return !row.getOrDefault("name", "").isBlank() && !row.getOrDefault("email", "").isBlank();
    }

    protected void afterImport(int saved) { }

    protected String name() { return getClass().getSimpleName(); }
}

// ---------- Subclasses fill in the blanks ----------
final class CsvImporter extends DataImporter {
    CsvImporter(List<Map<String, String>> db) { super(db); }
    protected List<Map<String, String>> parse(String text) {
        String[] lines = text.split("\n");
        String[] header = lines[0].split(",");
        List<Map<String, String>> rows = new ArrayList<>();
        for (int i = 1; i < lines.length; i++) {
            String[] cells = lines[i].split(",", -1);
            Map<String, String> row = new LinkedHashMap<>();
            for (int c = 0; c < header.length; c++) row.put(header[c], c < cells.length ? cells[c] : "");
            rows.add(row);
        }
        return rows;
    }
}

final class KeyValueImporter extends DataImporter {
    KeyValueImporter(List<Map<String, String>> db) { super(db); }
    protected List<Map<String, String>> parse(String text) {
        List<Map<String, String>> rows = new ArrayList<>();
        for (String line : text.split("\n")) {
            Map<String, String> row = new LinkedHashMap<>();
            for (String pair : line.split(";")) {
                String[] kv = pair.split("=", 2);
                row.put(kv[0], kv.length > 1 ? kv[1] : "");
            }
            rows.add(row);
        }
        return rows;
    }
    @Override protected boolean isValid(Map<String, String> row) {      // stricter: email must contain @
        return super.isValid(row) && row.get("email").contains("@");
    }
    @Override protected void afterImport(int saved) { System.out.println("  " + name() + " saved " + saved + ", notifying admin"); }
}

Both print:

  CsvImporter skipped {name=Bo, email=}
  KeyValueImporter skipped {name=Eli, email=not-an-email}
  KeyValueImporter saved 1, notifying admin
saved: 3 rows

(Python prints the dictionaries with quotes.) The parsers are deliberately simple: a real CSV importer must handle quoted fields that contain commas, so use csv in Python or a library such as OpenCSV or Apache Commons CSV in Java.

Abstract step or hook?

The base class owns the order; a hook is an optional step

  1. In code, the base class owns the order of the steps. A hook is an optional step with a default, like “does the customer want extras?”, which subclasses may override if they care.
Kind of stepHas a default?Subclass must override?Use for
Fixed step (private / not overridden)Yes, the only versionCannotThings that must be the same for all: saving, audit logging
Abstract stepNoYesThe reason the subclass exists: parsing
HookYes, often "do nothing" or "return true"NoOptional extras: stricter validation, notifications, "wants extras?"

Keep the number of abstract steps small. Every abstract method is a cost on every future subclass; a hook with a good default is cheaper.

A third partner who sends pipe-separated files is now one new class with one method. The template method, validation and saving are not touched.

Template Method versus Strategy: inheritance versus composition

The same problem can be solved with Strategy: keep one concrete Importer and pass the varying step in as an object or a function.

import java.util.*;
import java.util.function.Function;

public class ComposedDemo {
    // The same recipe, but the varying step is a strategy passed in, not a method overridden
    static final class Importer {
        private final Function<String, List<Map<String, String>>> parser;
        private final List<Map<String, String>> db;
        Importer(Function<String, List<Map<String, String>>> parser, List<Map<String, String>> db) {
            this.parser = parser; this.db = db;
        }
        int importText(String text) {
            List<Map<String, String>> good = new ArrayList<>();
            for (Map<String, String> row : parser.apply(text))
                if (!row.getOrDefault("email", "").isBlank()) good.add(row);
            db.addAll(good);
            return good.size();
        }
    }

    static List<Map<String, String>> pipeSeparated(String text) {
        List<Map<String, String>> rows = new ArrayList<>();
        for (String line : text.split("\n")) {
            String[] p = line.split("\\|", -1);
            rows.add(Map.of("name", p[0], "email", p.length > 1 ? p[1] : ""));
        }
        return rows;
    }

    public static void main(String[] args) {
        List<Map<String, String>> db = new ArrayList<>();
        Importer pipes = new Importer(ComposedDemo::pipeSeparated, db);   // pick the parser at run time
        System.out.println(pipes.importText("Fay|fay@example.com\nGus|"));  // 1
    }
}
Template MethodStrategy
MechanismInheritance: subclass overrides stepsComposition: the class has a step object or function
When is it chosen?When you pick which subclass to create; fixed for the object's lifeAt run time; can be swapped, even per call
Several varying stepsEasy: each is one method in the same subclassOne strategy per step, or one strategy object with several methods
Two independent dimensions (format × destination)Subclass explosion: CsvToDb, CsvToS3, JsonToDb…Combine freely: Importer(csvParser, s3Writer)
Shared state between stepsNatural: fields on the objectHas to be passed between the strategies
Testing a step aloneNeeds a subclass or the whole recipeCall the strategy directly

The rule of thumb many teams follow is "favour composition over inheritance": start with Strategy if the varying part could change at run time or vary along a second axis. Template Method is the right fit when the steps are tightly related, the variants are a genuine is a relationship (a CSV importer is a data importer), and the base class must guarantee that the steps run in order, such as audit logging always after saving.

Other look-alikes

  • Factory Method is often one step of a template method: the base class's recipe calls createParser(), and each subclass returns a different parser. The difference is what the step does: a factory method creates an object; a template method runs a whole algorithm. See Factory.
  • Callbacks and lambdas: a method that takes functions for the varying steps (retry(action, onFailure)) is a template method built with composition. Spring's JdbcTemplate and RestTemplate are named after the pattern but work this way: the template handles connections, errors and cleanup, and you pass a callback (RowMapper) for the part that varies.

When not to use it

Where you meet it in real code

Frameworks are full of template methods

  1. Frameworks are full of template methods. A test framework runs setUp(), your test, then tearDown(). A data importer always opens, parses, validates and saves, and each file format only fills in “parse”. Inheritance is a good fit here, because the subclass truly is a kind of the base recipe.
  • java.io.InputStream: read(byte[], int, int) is written once in the base class in terms of the abstract single-byte read(). A subclass implements one method and gets the rest (and overrides the bulk version for speed).
  • java.util.AbstractList: implement get() and size() and you get iteration, indexOf, contains, equals and hashCode for free.
  • HttpServlet.service() dispatches to doGet(), doPost() and the others; you override the ones you support, and the defaults answer "method not allowed".
  • Test frameworks: Python's unittest.TestCase runs setUp(), the test method, then tearDown(); JUnit does the same with annotated methods.
  • Python's socketserver.BaseRequestHandler calls setup(), handle() and finish(); Django's class-based views call get_queryset() and get_context_data() hooks from a fixed get().

In the interview

Your turn: a report exporter

A dashboard exports reports as CSV and HTML. Every export must: write a header with the report title and date, write each row, write a footer with the row count, and always record an audit entry, even if writing a row fails. HTML also needs an opening <table> and closing </table>. Sketch the base class, its template method and the HTML subclass.

Compare with our answer
abstract class ReportExporter {
    public final String export(Report r) {
        StringBuilder out = new StringBuilder();
        try {
            writeHeader(out, r);
            beforeRows(out);                         // hook
            for (List<String> row : r.rows()) writeRow(out, row);
            afterRows(out);                          // hook
            out.append(footer(r.rows().size()));
            return out.toString();
        } finally {
            audit(r);                                // always runs, even on failure
        }
    }
    protected abstract void writeHeader(StringBuilder out, Report r);
    protected abstract void writeRow(StringBuilder out, List<String> row);
    protected void beforeRows(StringBuilder out) { }
    protected void afterRows(StringBuilder out) { }
    protected String footer(int n) { return n + " rows\n"; }
    private void audit(Report r) { System.out.println("audit: exported " + r.title()); }
}

final class HtmlExporter extends ReportExporter {
    protected void writeHeader(StringBuilder out, Report r) { out.append("<h1>").append(r.title()).append("</h1>\n"); }
    protected void beforeRows(StringBuilder out) { out.append("<table>\n"); }
    protected void writeRow(StringBuilder out, List<String> row) {
        out.append("<tr>");
        for (String cell : row) out.append("<td>").append(escapeHtml(cell)).append("</td>");
        out.append("</tr>\n");
    }
    protected void afterRows(StringBuilder out) { out.append("</table>\n"); }
    protected String footer(int n) { return "<p>" + n + " rows</p>\n"; }
}

A strong answer mentions: a final (or documented) template method · header and row as abstract steps · <table> tags as hooks with empty defaults, so CSV ignores them · the audit in a finally block inside the template, so no subclass can skip it · escaping cell values in HTML · a footer hook that HTML overrides.

Template Method on one page
  • Intent: define an algorithm's skeleton once; subclasses fill in some steps without changing the order.
  • Roles: abstract class with a final template method · abstract steps (must override) · hooks (optional, with defaults) · concrete subclasses.
  • Hollywood principle: the base class calls the subclass, not the other way round.
  • Python: ABC + @abstractmethod enforces steps; @typing.final is only a type-checker hint.
  • Keep abstract steps few; prefer hooks with good defaults.
  • Versus Strategy: inheritance and fixed at creation vs composition and swappable; Strategy wins when a second axis varies.
  • Pitfalls: fragile base class, deep hierarchies, overridable calls from constructors.
  • In the wild: InputStream, AbstractList, HttpServlet.service(), unittest setUp/tearDown, Django views.
Your turn: the requirement changes

The importer must now save to either the database or an S3 bucket, chosen per partner, and a new partner sends JSON. With the current design that means CsvToDbImporter, CsvToS3Importer, JsonToDbImporter… How would you restructure it?

Compare with our answer

A strong answer mentions: recognising two independent axes (format and destination) and the subclass explosion they cause · keeping the template method for the fixed order (parse, validate, save, audit) · moving the destination out into a RowWriter strategy injected through the constructor (DbWriter, S3Writer), so the subclasses vary only by format · or going fully compositional, Importer(parser, writer), with no subclasses at all · choosing the combination per partner in one place (a config map or factory) · noting that the audit step stays in the base recipe so no combination can skip it.

Interactive labPractise it: build a recipe and add a new drinkOpens in the ByteAtlas lab. Your progress is saved in this browser.
Check what stuck

1. Three payment providers each need: validate the order, call the provider's authorise API, record the transaction, send a receipt. Only the authorise call differs, and audit rules require that recording always follows authorisation. Which design fits best?

2. What is a hook in the Template Method pattern?

3. A team has CsvToDbExporter, CsvToS3Exporter, JsonToDbExporter and JsonToS3Exporter, all subclasses of one template. Adding XML would mean two more classes. What is the best fix?

4. A Java base class calls the overridable configure() hook from its constructor. A subclass overrides configure() and reads its own non-final field timeout, declared as int timeout = 30. What value does it see?

5. Why is the template method usually declared final in Java?

6. Which of these is the best example of Template Method in a standard library?

7. Spring's JdbcTemplate handles connections and errors and takes a RowMapper callback for each row. Which statement is most accurate?

Score 60% or more and the lesson is marked complete.

Passing the quiz also marks it complete. Progress is saved in this browser only.