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.
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.
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?” |
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.
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.
(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.
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.
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.
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); }
}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 bothWatch the skeleton run: load, drop cancelled, header, rows, totals if wanted, save. And now both files say 41.
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.)
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.
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.
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); // 4Ask 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.
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.
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.
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 is often compared with the Strategy pattern. Both let you vary part of an algorithm.
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 | 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.
Use it when:
Skip it when:
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.
final and fixes the order; shared steps live there, once.Fix the skeleton. Fill in the steps.
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"));
}
}