# Template Method PatternSame 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.*

{{< lesson-video youtube="DFp46ho8Y1Q" title="Template Method Pattern" >}}

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

```mermaid {alt="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." caption="The same algorithm, written twice, already disagrees."}
flowchart TD
  R["November sales report"] --> C["CsvExporter<br/>load, drop cancelled,<br/>header, rows, save"]
  R --> P["PdfExporter<br/>load, (missing),<br/>header, rows, save"]
  C --> C1(["41 orders"])
  P --> P1(["43 orders"])
  class R muted
  class C c1
  class P c4
  class P1 bad
```

## 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.

```mermaid {alt="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." caption="The office fixes the order; you fill in the blanks; some boxes are optional."}
flowchart TD
  F["the form: fixed order"] --> N["1. Name ____"]
  N --> A["2. Address ____"]
  A --> D["3. Details ____"]
  D --> E["4. Anything else? (optional)"]
  E --> S["5. Signature ____"]
  class F c6
  class N,A,D,S hl
  class E c2
```

That gives us three words:

| Word | Meaning | On the form |
|---|---|---|
| **Template method** | the fixed sequence of steps | the printed form, in its order |
| **Steps** (primitive operations) | the blanks every variant must fill in | name, address, details, signature |
| **Hooks** | optional 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.

```java
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.

```mermaid {alt="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." caption="Four copies of the order, four chances to drift."}
flowchart LR
  FIX["fix: drop cancelled"] --> C["CsvExporter: all steps"]
  FIX -.->|"?"| P["PdfExporter: forgot a step"]
  FIX -.->|"?"| X["ExcelExporter: swapped two"]
  FIX -.->|"?"| J["JsonExporter: copy #4"]
  class FIX c2
  class C c1
  class P,X bad
  class J c5
```

(When one change has to be repeated in many classes like this, it's the
[Shotgun Surgery](/code-smells/shotgun-surgery/) smell; and each `export` keeps growing into a
[Long Method](/code-smells/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.

```mermaid {alt="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." caption="One skeleton in the base class; each subclass fills the blanks."}
flowchart LR
  subgraph SK["ReportExporter.export(): the skeleton"]
    direction TB
    L["load rows"] --> D["drop cancelled"] --> H["writeHeader()"] --> W["writeRow(row) × n"] --> T["totals? (hook)"] --> S["save(file)"]
  end
  subgraph PDF["PdfExporter fills in"]
    direction TB
    P1["addTitle(...)"] --> P2["pdf.addLine(...)"] --> P3["pdf.save(file)"]
  end
  SK ~~~ PDF
  class L,D c6
  class H,W,S hl
  class T c2
  class P1,P2,P3 c4
```

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.

```java
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:

```java
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); }
}
```

```mermaid {alt="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." caption="One final template method, three abstract steps, two hooks."}
classDiagram
  class ReportExporter {
    <<abstract>>
    +export(Report, Path) void
    #writeHeader() void*
    #writeRow(Row) void*
    #save(Path) void*
    #wantsTotals() boolean
    #writeTotals(rows) void
  }
  class CsvExporter {
    -StringBuilder out
    #writeHeader()
    #writeRow(Row)
    #save(Path)
  }
  class PdfExporter {
    -PdfDoc pdf
    #writeHeader()
    #writeRow(Row)
    #wantsTotals() boolean
    #writeTotals(rows)
    #save(Path)
  }
  ReportExporter <|-- CsvExporter
  ReportExporter <|-- PdfExporter
  note for ReportExporter "export() is final: the order never changes"
```

The client just calls `export`:

```java
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.

```mermaid {alt="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." caption="The base class calls the subclass, step by step."}
sequenceDiagram
  participant C as Client
  participant B as ReportExporter.export()
  participant P as PdfExporter
  C->>B: export(november, "sales.pdf")
  Note over B: load rows, drop cancelled
  B->>P: writeHeader()
  loop every row
    B->>P: writeRow(row)
  end
  B->>P: wantsTotals()
  P-->>B: true
  B->>P: writeTotals(rows)
  B->>P: save(file)
```

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:

| Kind | In `ReportExporter` | Rule |
|---|---|---|
| **Template method** | `export()` | `final`: fixes the order; subclasses can't reorder or skip steps |
| **Abstract step** | `writeHeader()`, `writeRow()`, `save()` | must be filled in; the compiler won't let a subclass forget one |
| **Hook** | `wantsTotals()`, `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**.

```mermaid {alt="The base class ReportExporter decides when and calls down into PdfExporter's steps; PdfExporter supplies what and never calls export from inside a step." caption="Don't call us, we'll call you."}
flowchart TD
  B["ReportExporter<br/>decides when"] -->|"we call you:<br/>writeRow(row)"| P["PdfExporter<br/>supplies what"]
  P -.->|"you don't call us"| X["export()<br/>never called from a step"]
  class B c6
  class P c4
  class X bad
```

> **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`.

```java
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.

```mermaid {alt="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." caption="contains() is a template method built on your get() and size()."}
sequenceDiagram
  participant U as Caller
  participant A as AbstractList.contains()
  participant N as NumberRange
  U->>A: contains(3)
  A->>N: size()
  N-->>A: 5
  A->>N: get(0)
  N-->>A: 1
  A->>N: get(1)
  N-->>A: 2
  A->>N: get(2)
  N-->>A: 3
  A-->>U: true
```

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.

```mermaid {alt="A change to one step of ReportExporter's skeleton ripples into every subclass: CsvExporter, PdfExporter and ExcelExporter may all break." caption="Change the skeleton, and every subclass feels it."}
flowchart LR
  B["ReportExporter<br/>changes a step"] --> C["CsvExporter"]
  B --> P["PdfExporter"]
  B --> E["ExcelExporter"]
  class B bad
  class C,P,E warn
```

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**:

```java
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](/code-smells/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](/patterns/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:

```java
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);
    }
}
```

```mermaid {alt="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." caption="Inheritance fixes the choice; composition lets you swap it."}
flowchart LR
  subgraph TM["Template Method: is a"]
    direction TB
    B1["ReportExporter (abstract)"] --> C1["CsvExporter"]
    B1 --> P1["PdfExporter"]
  end
  subgraph ST["Strategy: has a"]
    direction TB
    B2["ReportExporter"] -->|"holds"| F["ReportFormat"]
    F -.-> C2["CsvFormat"]
    F -.-> P2["PdfFormat"]
  end
  TM ~~~ ST
  class B1,B2 c6
  class C1,C2 c1
  class P1,P2 c4
  class F c5
```

| | **Template Method** | **Strategy** |
|---|---|---|
| Mechanism | inheritance (override steps) | composition (pass in an object) |
| When the choice is made | when you pick the subclass | at run time; can be swapped |
| Steps can share state | yes, the object's own fields | only what you pass in |
| Combining variations | one subclass per combination | mix 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.

```mermaid {alt="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." caption="When a fixed skeleton pays for itself."}
flowchart TD
  Q1{"Same steps,<br/>same order?"}
  Q1 -->|no| K1["No shared skeleton"]
  Q1 -->|yes| Q2{"Swap at run time<br/>or combine?"}
  Q2 -->|yes| S["Strategy"]
  Q2 -->|no| Q3{"Only a few<br/>steps differ?"}
  Q3 -->|yes| U["Template Method"]
  Q3 -->|no| K2["Split it, or compose"]
  class U good
  class S c5
  class K1,K2 muted
```

## 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.

```mermaid {alt="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." caption="Fix the skeleton. Fill in the steps."}
flowchart LR
  A["duplicated algorithms<br/>drift apart"] --> B["one final<br/>template method"]
  B --> C["abstract steps<br/>+ hooks"]
  C --> D["subclasses fill in,<br/>the base calls them"]
  class A bad
  class B c6
  class C hl
  class D good
```

- 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):

```java
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"));
    }
}
```
