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.
On this page
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
- 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
- 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.
- 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".
| Role | In this example | Responsibility |
|---|---|---|
| Abstract class | DataImporter | Holds the template method importText() and the fixed steps |
| Template method | importText() | Calls the steps in order; final so subclasses can't change the order |
| Primitive operations (abstract steps) | parse() | Must be implemented by every subclass |
| Hooks | isValid(), afterImport() | Optional steps with a default; subclasses override only if they care |
| Concrete classes | CsvImporter, KeyValueImporter | Fill 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"); }
}from abc import ABC, abstractmethod
from typing import final
# ---------- The base class owns the recipe ----------
class DataImporter(ABC):
def __init__(self, db: list):
self.db = db
@final # a hint for type checkers; Python itself won't stop an override
def import_text(self, text: str) -> int:
"""The template method."""
rows = self.parse(text) # 1. varies: abstract
good = []
for row in rows: # 2. fixed, with a hook inside
if self.is_valid(row):
good.append(row)
else:
print(f" {type(self).__name__} skipped {row}")
self.db.extend(good) # 3. fixed
self.after_import(len(good)) # 4. hook: does nothing by default
return len(good)
@abstractmethod
def parse(self, text: str) -> list[dict]: ...
def is_valid(self, row: dict) -> bool: # hook with a sensible default
return bool(row.get("name", "").strip()) and bool(row.get("email", "").strip())
def after_import(self, saved: int) -> None:
pass
# ---------- Subclasses fill in the blanks ----------
class CsvImporter(DataImporter):
def parse(self, text):
header, *lines = text.split("\n")
keys = header.split(",")
rows = []
for line in lines:
cells = line.split(",")
rows.append({k: cells[i] if i < len(cells) else "" for i, k in enumerate(keys)})
return rows
class KeyValueImporter(DataImporter):
def parse(self, text):
rows = []
for line in text.split("\n"):
pairs = (p.split("=", 1) for p in line.split(";"))
rows.append({kv[0]: kv[1] if len(kv) > 1 else "" for kv in pairs})
return rows
def is_valid(self, row): # stricter: email must contain @
return super().is_valid(row) and "@" in row["email"]
def after_import(self, saved):
print(f" {type(self).__name__} saved {saved}, notifying admin")
# ---------- Client ----------
if __name__ == "__main__":
db = []
csv = "name,email\nAna,ana@example.com\nBo,\nCy,cy@example.com"
kv = "name=Dee;email=dee@example.com\nname=Eli;email=not-an-email"
CsvImporter(db).import_text(csv)
KeyValueImporter(db).import_text(kv)
print(f"saved: {len(db)} rows")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
- 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 step | Has a default? | Subclass must override? | Use for |
|---|---|---|---|
Fixed step (private / not overridden) | Yes, the only version | Cannot | Things that must be the same for all: saving, audit logging |
| Abstract step | No | Yes | The reason the subclass exists: parsing |
| Hook | Yes, often "do nothing" or "return true" | No | Optional 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
}
}from typing import Callable
Parser = Callable[[str], list[dict]]
class Importer:
"""The same recipe, but the varying step is a function passed in, not a method overridden."""
def __init__(self, parser: Parser, db: list):
self.parser, self.db = parser, db
def import_text(self, text: str) -> int:
good = [row for row in self.parser(text) if row.get("email", "").strip()]
self.db.extend(good)
return len(good)
def pipe_separated(text):
rows = []
for line in text.split("\n"):
name, _, email = line.partition("|")
rows.append({"name": name, "email": email})
return rows
db = []
pipes = Importer(pipe_separated, db) # pick the parser at run time
print(pipes.import_text("Fay|fay@example.com\nGus|")) # 1| Template Method | Strategy | |
|---|---|---|
| Mechanism | Inheritance: subclass overrides steps | Composition: the class has a step object or function |
| When is it chosen? | When you pick which subclass to create; fixed for the object's life | At run time; can be swapped, even per call |
| Several varying steps | Easy: each is one method in the same subclass | One 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 steps | Natural: fields on the object | Has to be passed between the strategies |
| Testing a step alone | Needs a subclass or the whole recipe | Call 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'sJdbcTemplateandRestTemplateare 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
- 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-byteread(). A subclass implements one method and gets the rest (and overrides the bulk version for speed).java.util.AbstractList: implementget()andsize()and you get iteration,indexOf,contains,equalsandhashCodefor free.HttpServlet.service()dispatches todoGet(),doPost()and the others; you override the ones you support, and the defaults answer "method not allowed".- Test frameworks: Python's
unittest.TestCaserunssetUp(), the test method, thentearDown(); JUnit does the same with annotated methods. - Python's
socketserver.BaseRequestHandlercallssetup(),handle()andfinish(); Django's class-based views callget_queryset()andget_context_data()hooks from a fixedget().
In the interview
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"; }
}from abc import ABC, abstractmethod
from html import escape
class ReportExporter(ABC):
def export(self, report) -> str: # the template method
out = []
try:
self.write_header(out, report)
self.before_rows(out) # hook
for row in report.rows:
self.write_row(out, row)
self.after_rows(out) # hook
out.append(self.footer(len(report.rows)))
return "".join(out)
finally:
print(f"audit: exported {report.title}") # always runs, even on failure
@abstractmethod
def write_header(self, out, report): ...
@abstractmethod
def write_row(self, out, row): ...
def before_rows(self, out): pass
def after_rows(self, out): pass
def footer(self, n): return f"{n} rows\n"
class HtmlExporter(ReportExporter):
def write_header(self, out, report): out.append(f"<h1>{escape(report.title)}</h1>\n")
def before_rows(self, out): out.append("<table>\n")
def write_row(self, out, row):
out.append("<tr>" + "".join(f"<td>{escape(c)}</td>" for c in row) + "</tr>\n")
def after_rows(self, out): out.append("</table>\n")
def footer(self, n): return f"<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.
- Intent: define an algorithm's skeleton once; subclasses fill in some steps without changing the order.
- Roles: abstract class with a
finaltemplate 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+@abstractmethodenforces steps;@typing.finalis 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(),unittestsetUp/tearDown, Django views.
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.
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?
The steps and their order are fixed and only one step varies, so the base class owns the recipe and guarantees the order. Independent classes copy the steps; a branch grows with every provider.
2. What is a hook in the Template Method pattern?
Abstract steps are mandatory; hooks are optional extras with defaults, such as "do nothing" or "return true". The final method that runs the steps is the template method itself.
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?
Two independent axes cause a subclass explosion. Composition lets the format and the destination vary separately: formats × destinations classes become formats + destinations.
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?
The base constructor runs before the subclass's field initialisers, so the override sees default values (0, null). Java compiles this without complaint, which is why "never call overridable methods from a constructor" is a standard rule.
5. Why is the template method usually declared final in Java?
The point of the pattern is a guaranteed order. final stops a subclass from overriding the recipe; the abstract steps and hooks remain overridable.
6. Which of these is the best example of Template Method in a standard library?
AbstractList implements its other methods in terms of two abstract steps that subclasses supply. Passing a comparator is Strategy; the executor factory is a factory method.
7. Spring's JdbcTemplate handles connections and errors and takes a RowMapper callback for each row. Which statement is most accurate?
You don't subclass JdbcTemplate; you pass a callback. The fixed skeleton (open, execute, map, close, translate errors) is the template idea, implemented with a strategy-style callback.
Score 60% or more and the lesson is marked complete.