Template Method Pattern

November 24, 202612 minutes

Same report, two answers. Learn how the Template Method pattern fixes the skeleton of an algorithm and lets subclasses fill in the steps, with diagrams, Java code, and a narrated video.

Your app exports the monthly sales report in two formats: a spreadsheet file (CSV) and a PDF. Same report, same month. But the spreadsheet says 41 orders, and the PDF says 43. Which one is right? Look at the steps: both exporters load the rows, write a header, write every row, and save. But only one of them drops the cancelled orders. Someone fixed a bug, in one place. The same steps, written twice, drift apart. The fix has a name: the Template Method pattern. Fix the skeleton. Fill in the steps.

Prefer to watch? The narrated video above covers the same lesson (about 9 minutes). The article follows it section by section, with diagrams, a little extra depth, and the complete code.

Same report, two answers

The November sales report is exported twice: CsvExporter produces 41 orders because it drops cancelled orders; PdfExporter produces 43 orders because its copy of the steps is missing that step. The November sales report is exported twice: CsvExporter produces 41 orders because it drops cancelled orders; PdfExporter produces 43 orders because its copy of the steps is missing that step.
The same algorithm, written twice, already disagrees.

The fill-in form

Think of an application form. The office prints the sections in a fixed order: your name, your address, your details, and a signature at the end. You don’t choose the order, and you can’t skip the signature. You only fill in the blanks. Some boxes are optional, like “Anything else you’d like to add?”: leave it empty, and that’s fine. Two people fill in the same form and get two different results, but the shape is always the same.

An application form with fixed sections: name, address and details are blanks you must fill in; anything else is an optional box; the signature is a blank you must fill in. The office fixes the order. An application form with fixed sections: name, address and details are blanks you must fill in; anything else is an optional box; the signature is a blank you must fill in. The office fixes the order.
The office fixes the order; you fill in the blanks; some boxes are optional.

That gives us three words:

WordMeaningOn the form
Template methodthe fixed sequence of stepsthe printed form, in its order
Steps (primitive operations)the blanks every variant must fill inname, address, details, signature
Hooksoptional steps with a default“anything else?”

The obvious way: two exporters, each with the whole algorithm

Back to the exporters. The obvious first version is one class per format, each with its own complete export method. Both load the rows, both write a header, then every row, then save the file: the same steps, in the same order.

class CsvExporter {
    void export(Report report, Path file) throws IOException {
        List<Row> rows = report.load();
        rows.removeIf(Row::isCancelled);                  // fixed last month
        StringBuilder out = new StringBuilder("date,customer,total\n");
        for (Row row : rows) out.append(row.toCsv()).append("\n");
        Files.writeString(file, out);
    }
}

class PdfExporter {
    void export(Report report, Path file) throws IOException {
        List<Row> rows = report.load();                   // cancelled orders still in
        PdfDoc pdf = new PdfDoc();
        pdf.addTitle("Sales report");
        for (Row row : rows) pdf.addLine(row.date(), row.customer(), row.total());
        pdf.save(file);
    }
}

But look closely. Last month, someone added a line to the spreadsheet exporter to drop cancelled orders. The PDF exporter never got it. It’s easy to write, and each class reads nicely from top to bottom. But it’s one algorithm, written twice.

Why it breaks: drift, and every new format is another copy

Now the product team wants Excel, and JSON: two more copies of the same algorithm. Every copy holds its own version of the order. One forgets a step. Another swaps two of them. And every fix has to be applied to every copy; nothing makes sure that every format runs the same steps, in the same order.

Four exporters each hold their own copy of the steps: Csv has all five, Pdf is missing drop cancelled, Excel writes rows before the header, Json has all five; a fix applied to Csv doesn't reach the others. Four exporters each hold their own copy of the steps: Csv has all five, Pdf is missing drop cancelled, Excel writes rows before the header, Json has all five; a fix applied to Csv doesn't reach the others.
Four copies of the order, four chances to drift.

(When one change has to be repeated in many classes like this, it’s the Shotgun Surgery smell; and each export keeps growing into a Long Method.)

The order is duplicated, so it drifts.

The key insight: the base class owns the skeleton

Here’s the key insight. The order of the steps is the thing to share. So move it into one method, in an abstract base class. The steps that are the same for everyone, like loading the rows and dropping cancelled orders, are written once, right there. The steps that differ become blanks: abstract methods. Write the header. Write a row. Save the file. Each format is a subclass that fills in the blanks: the spreadsheet fills them one way, the PDF another.

ReportExporter.export is the skeleton: load rows and drop cancelled are shared steps written once; writeHeader, writeRow and save are blanks; totals is an optional hook. CsvExporter and PdfExporter each fill the blanks with their own code. ReportExporter.export is the skeleton: load rows and drop cancelled are shared steps written once; writeHeader, writeRow and save are blanks; totals is an optional hook. CsvExporter and PdfExporter each fill the blanks with their own code.
One skeleton in the base class; each subclass fills the blanks.

And notice who calls whom. The base class runs the show, and calls the subclass when it’s time. The subclass never calls the base class’s algorithm. That’s the Hollywood Principle: don’t call us, we’ll call you.

Fix the skeleton. Fill in the steps.

Building it in Java

In Java, the base class is ReportExporter. Its export method is the template method: it’s public, and it’s final, so no subclass can change the order. It loads the rows and drops the cancelled orders itself. Then it calls writeHeader, writeRow for every row, and save: those three are abstract. And there are two hooks: wantsTotals returns false by default, and writeTotals does nothing by default. A subclass may override them, but doesn’t have to.

abstract class ReportExporter {
    public final void export(Report report, Path file) throws IOException {
        List<Row> rows = report.load();
        rows.removeIf(Row::isCancelled);
        writeHeader();
        for (Row row : rows) {
            writeRow(row);
        }
        if (wantsTotals()) {
            writeTotals(rows);
        }
        save(file);
    }

    protected abstract void writeHeader();
    protected abstract void writeRow(Row row);
    protected abstract void save(Path file) throws IOException;

    protected boolean wantsTotals() { return false; }      // a hook: override if you like
    protected void writeTotals(List<Row> rows) { }         // a hook with an empty default
}

The spreadsheet exporter fills in the three steps; that’s all it has to write. The PDF exporter fills in the same three, and also turns on the totals hook:

class CsvExporter extends ReportExporter {
    private final StringBuilder out = new StringBuilder();

    protected void writeHeader()     { out.append("date,customer,total\n"); }
    protected void writeRow(Row row) { out.append(row.toCsv()).append("\n"); }
    protected void save(Path file) throws IOException { Files.writeString(file, out); }
}

class PdfExporter extends ReportExporter {
    private final PdfDoc pdf = new PdfDoc();

    protected void writeHeader()     { pdf.addTitle("Sales report"); }
    protected void writeRow(Row row) { pdf.addLine(row.date(), row.customer(), row.total()); }
    protected boolean wantsTotals()  { return true; }
    protected void writeTotals(List<Row> rows) { pdf.addTotal(Row.sum(rows)); }
    protected void save(Path file) throws IOException { pdf.save(file); }
}
Class diagram: the abstract ReportExporter has a final export method, three abstract protected steps writeHeader, writeRow and save, and two hooks wantsTotals and writeTotals; CsvExporter overrides the three steps; PdfExporter overrides the three steps and both hooks. Class diagram: the abstract ReportExporter has a final export method, three abstract protected steps writeHeader, writeRow and save, and two hooks wantsTotals and writeTotals; CsvExporter overrides the three steps; PdfExporter overrides the three steps and both hooks.
One final template method, three abstract steps, two hooks.

The client just calls export:

new CsvExporter().export(november, Path.of("sales.csv"));
new PdfExporter().export(november, Path.of("sales.pdf"));   // same steps: 41 orders in both

Watch the skeleton run: load, drop cancelled, header, rows, totals if wanted, save. And now both files say 41.

Sequence: the client calls export on PdfExporter; the inherited ReportExporter.export loads the rows and drops cancelled orders, then calls writeHeader, writeRow for each row, wantsTotals which returns true, writeTotals, and save, all implemented by PdfExporter. Sequence: the client calls export on PdfExporter; the inherited ReportExporter.export loads the rows and drops cancelled orders, then calls writeHeader, writeRow for each row, wantsTotals which returns true, writeTotals, and save, all implemented by PdfExporter.
The base class calls the subclass, step by step.

The cancelled-orders rule now lives in exactly one place. Fix it there, and every format gets the fix, including the formats nobody has written yet. (These exporters keep their output in a field, so create a new exporter for each export.)

Anatomy: final, abstract steps, hooks, and the Hollywood Principle

There are three kinds of method:

KindIn ReportExporterRule
Template methodexport()final: fixes the order; subclasses can’t reorder or skip steps
Abstract stepwriteHeader(), writeRow(), save()must be filled in; the compiler won’t let a subclass forget one
HookwantsTotals(), writeTotals()has a default (false, an empty body); may be overridden

All the steps are protected, because they’re meant for subclasses, not for callers. The base class decides when; the subclass only supplies what.

The base class ReportExporter decides when and calls down into PdfExporter's steps; PdfExporter supplies what and never calls export from inside a step. The base class ReportExporter decides when and calls down into PdfExporter's steps; PdfExporter supplies what and never calls export from inside a step.
Don't call us, we'll call you.

Don’t call us, we’ll call you.

Keep the number of steps and hooks small: every hook is a promise the base class has to keep forever, and a subclass reader has to understand all of them to know what runs.

You already use it: AbstractList

Java’s AbstractList is full of template methods. Here’s a list of the numbers from one to five. You write just two methods, get and size, and you inherit dozens: contains, indexOf, iteration, equals, toString, subList. Each one is a template method that calls your get and size.

class NumberRange extends AbstractList<Integer> {
    private final int from, to;

    NumberRange(int from, int to) { this.from = from; this.to = to; }

    public Integer get(int i) { return from + i; }
    public int size()         { return to - from; }
}

List<Integer> range = new NumberRange(1, 6);   // 1, 2, 3, 4, 5
range.contains(3);    // true: AbstractList's contains() calls your get() and size()
range.indexOf(5);     // 4

Ask it whether it contains 3, and AbstractList calls your get, again and again, until it finds it. You wrote the steps. You inherited the algorithm.

Sequence: the caller asks range.contains(3); AbstractList's inherited contains loops, calling NumberRange.size and then get(0), get(1) and get(2), which returns 3, so contains returns true. Sequence: the caller asks range.contains(3); AbstractList's inherited contains loops, calling NumberRange.size and then get(0), get(1) and get(2), which returns 3, so contains returns true.
contains() is a template method built on your get() and size().

Servlets work the same way. HttpServlet.service() is the template, and it calls your doGet, or your doPost, when a request arrives. JUnit’s lifecycle (set up, run the test, tear down) and java.io.InputStream (read(byte[]) built on your single-byte read()) are more of the same.

Pitfalls: fragile base classes and subclasses that fight the skeleton

Inheritance couples tightly. Change the skeleton in the base class (call writeHeader after the rows, add a step, change a default) and every subclass can break. That’s the fragile base class problem.

A change to one step of ReportExporter's skeleton ripples into every subclass: CsvExporter, PdfExporter and ExcelExporter may all break. A change to one step of ReportExporter's skeleton ripples into every subclass: CsvExporter, PdfExporter and ExcelExporter may all break.
Change the skeleton, and every subclass feels it.

And sometimes a subclass doesn’t fit the skeleton. A JSON exporter needs commas between the rows. The skeleton has no step for that, so it writes a comma after every row and then cuts the last one off when it saves. It’s fighting the skeleton:

class JsonExporter extends ReportExporter {
    private final StringBuilder out = new StringBuilder();

    protected void writeHeader()     { out.append("["); }
    protected void writeRow(Row row) { out.append(row.toJson()).append(","); }  // comma after each row...
    protected void save(Path file) throws IOException {
        out.setLength(out.length() - 1);                  // ...so cut the last one off
        Files.writeString(file, out.append("]"));
    }
}

Other subclasses override steps with empty bodies, or throw an exception that says “not supported”. A subclass that refuses what it inherits is a code smell called Refused Bequest.

The fix is to change the skeleton: add a better step, like a writeSeparator() hook called between rows; split the algorithm into two templates; or switch to composition (next section).

If subclasses fight the skeleton, the skeleton is wrong.

Template Method vs Strategy

Template Method is often compared with the Strategy pattern. Both let you vary part of an algorithm.

  • Template Method uses inheritance. The steps are methods a subclass overrides. You pick the behavior when you pick the class, and it can’t change later.
  • Strategy uses composition. The varying part is an object you pass in. You can swap it at run time, and mix and match.

Here’s the same exporter, with a strategy. It holds a ReportFormat object and calls it for each step:

class ReportExporter {
    private final ReportFormat format;                    // composition: a strategy
    ReportExporter(ReportFormat format) { this.format = format; }

    void export(Report report, Path file) throws IOException {
        List<Row> rows = report.load();
        rows.removeIf(Row::isCancelled);
        format.writeHeader();
        for (Row row : rows) format.writeRow(row);
        format.save(file);
    }
}
Template Method: CsvExporter and PdfExporter extend ReportExporter, an is-a relationship fixed when you pick the class. Strategy: ReportExporter has a ReportFormat, and CsvFormat or PdfFormat can be plugged in and swapped at run time. Template Method: CsvExporter and PdfExporter extend ReportExporter, an is-a relationship fixed when you pick the class. Strategy: ReportExporter has a ReportFormat, and CsvFormat or PdfFormat can be plugged in and swapped at run time.
Inheritance fixes the choice; composition lets you swap it.
Template MethodStrategy
Mechanisminheritance (override steps)composition (pass in an object)
When the choice is madewhen you pick the subclassat run time; can be swapped
Steps can share stateyes, the object’s own fieldsonly what you pass in
Combining variationsone subclass per combinationmix and match objects

A good rule of thumb: if the steps need the object’s own state and never change at run time, Template Method is simple and fine. If they vary on their own, or need swapping, prefer composition. (A Template Method skeleton can also live inside a Strategy, or call one.)

Template Method inherits the steps. Strategy plugs them in.

When to use it (and when not to)

Use it when:

  • ✓ several classes run the same steps in the same order, and differ in only a few of them,
  • ✓ you must guarantee the order, and a step that always runs (drop cancelled orders, close the file, release a lock),
  • ✓ you’re writing a base class or framework for others to extend.

Skip it when:

  • ✗ the variants differ in more than a few steps,
  • ✗ the behavior should be swapped at run time, or combined: that’s a strategy,
  • ✗ the class already needs a different superclass (Java has single inheritance),
  • ✗ subclasses start fighting the skeleton: change the skeleton.
Decision flowchart: if variants don't share the same steps in the same order, don't use the pattern; if the varying part must be swapped at run time or combined, use Strategy; otherwise if only a few steps differ, use Template Method; if many differ, split the algorithm or use composition. Decision flowchart: if variants don't share the same steps in the same order, don't use the pattern; if the varying part must be swapped at run time or combined, use Strategy; otherwise if only a few steps differ, use Template Method; if many differ, split the algorithm or use composition.
When a fixed skeleton pays for itself.

Recap

Duplicated algorithms drift apart. Instead, put the order in one final template method. Turn the parts that differ into abstract steps and hooks. Subclasses fill them in, and the base class calls them.

Recap chain: duplicated algorithms drift apart; one final template method holds the order; abstract steps and hooks mark what varies; subclasses fill them in and the base class calls them. Recap chain: duplicated algorithms drift apart; one final template method holds the order; abstract steps and hooks mark what varies; subclasses fill them in and the base class calls them.
Fix the skeleton. Fill in the steps.
  • The template method is final and fixes the order; shared steps live there, once.
  • Abstract steps must be filled in; hooks have defaults.
  • Don’t call us, we’ll call you: the base class calls the subclass.
  • Watch for fragile base classes and subclasses that fight the skeleton (Refused Bequest).
  • Template Method inherits the steps. Strategy plugs them in.

Fix the skeleton. Fill in the steps.

Complete code

For reference, the exporters written out so they compile (with tiny stand-ins for the report and the PDF library):

import java.io.IOException;
import java.nio.file.*;
import java.util.*;

record Row(String date, String customer, int total, boolean isCancelled) {
    String toCsv() { return date + "," + customer + "," + total; }
    String toJson() { return "{\"date\":\"" + date + "\",\"customer\":\"" + customer + "\",\"total\":" + total + "}"; }
    static int sum(List<Row> rows) { return rows.stream().mapToInt(Row::total).sum(); }
}

record Report(List<Row> rows) {
    List<Row> load() { return new ArrayList<>(rows); }
}

class PdfDoc {   // stand-in for a real PDF library
    private final StringBuilder text = new StringBuilder();
    void addTitle(String t) { text.append("# ").append(t).append('\n'); }
    void addLine(String date, String customer, int total) { text.append(date + "  " + customer + "  " + total + '\n'); }
    void addTotal(int total) { text.append("TOTAL ").append(total).append('\n'); }
    void save(Path file) throws IOException { Files.writeString(file, text); }
}

abstract class ReportExporter {
    public final void export(Report report, Path file) throws IOException {
        List<Row> rows = report.load();
        rows.removeIf(Row::isCancelled);
        writeHeader();
        for (Row row : rows) {
            writeRow(row);
        }
        if (wantsTotals()) {
            writeTotals(rows);
        }
        save(file);
    }

    protected abstract void writeHeader();
    protected abstract void writeRow(Row row);
    protected abstract void save(Path file) throws IOException;

    protected boolean wantsTotals() { return false; }
    protected void writeTotals(List<Row> rows) { }
}

class CsvExporter extends ReportExporter {
    private final StringBuilder out = new StringBuilder();

    protected void writeHeader()     { out.append("date,customer,total\n"); }
    protected void writeRow(Row row) { out.append(row.toCsv()).append("\n"); }
    protected void save(Path file) throws IOException { Files.writeString(file, out); }
}

class PdfExporter extends ReportExporter {
    private final PdfDoc pdf = new PdfDoc();

    protected void writeHeader()     { pdf.addTitle("Sales report"); }
    protected void writeRow(Row row) { pdf.addLine(row.date(), row.customer(), row.total()); }
    protected boolean wantsTotals()  { return true; }
    protected void writeTotals(List<Row> rows) { pdf.addTotal(Row.sum(rows)); }
    protected void save(Path file) throws IOException { pdf.save(file); }
}

public class Exports {
    public static void main(String[] args) throws IOException {
        Report november = new Report(List.of(
            new Row("2026-11-02", "Ana", 120, false),
            new Row("2026-11-05", "Ben", 80, true),      // cancelled: skipped by every format
            new Row("2026-11-09", "Chen", 45, false)));

        new CsvExporter().export(november, Path.of("sales.csv"));
        new PdfExporter().export(november, Path.of("sales.pdf"));
    }
}