Template Method writes an algorithm's outline once, in a base class method, as a fixed sequence of steps. Some steps are abstract and every subclass must write them; some are hooks with a default that a subclass may override; the rest are fixed. Subclasses fill in the blanks but cannot change the order, so every variant runs the same skeleton. It is how frameworks hand control to your code: you override doGet() or handle(), and the framework decides when to call it.
Think of it like
A franchise operations manual
Every branch of a coffee chain opens the same way: unlock, run the safety check, set up the counter, open the doors. Head office wrote that checklist, and no branch may reorder it or skip the safety check. One line says "set up the local menu board", and each branch does that its own way. Another says "play music (optional, head office's playlist by default)". The checklist is the template method, the menu-board line is an abstract step, the music line is a hook, and the branches are the subclasses. Head office never phones a branch to ask how to open: the checklist calls on the branch when its line comes up.
The problem
A store imports product codes from suppliers. The first supplier sent CSV, so someone wrote CsvImporter. A partner then sent JSON, so someone copied the class into JsonImporter, changed the parse line and, while there, added a check that rejects bad rows. This is the Before version in the visualizer above.
class CsvImporter {
constructor(private db: Db) {}
run(text: string) {
const rows = text.split(",").map(Number);
this.db.insert(rows);
return `saved ${rows.length}`;
}
}
class JsonImporter {
constructor(private db: Db) {}
run(text: string) {
const rows: number[] = JSON.parse(text);
const ok =
rows.every((r) => r > 0) &&
new Set(rows).size === rows.length;
if (!ok) {
return "rejected";
}
this.db.insert(rows);
return `saved ${rows.length}`;
}
}Read the two run() methods side by side: parse, check, save, report. The outline is the same and only the parse line truly differs. But the copies have already drifted: the CSV copy never got the check. A CSV row 1,,3 has a blank cell, Number("") is 0, and code 0 lands in the database. Run the Before version and watch db.rows end up holding a 0.
- The algorithm exists twice. Every fix to the outline (a new check, logging, a transaction around the save) has to be made in every copy, and nothing reminds you to.
- Copies drift. Here the drift is a real bug: one format validates and the other does not, and both classes look correct on their own.
- Nothing enforces the order. A copy could save before validating, or forget to save at all. The rule "parse, then check, then save" lives only in people's heads.
- A new format means a new copy. XML would start by copying a whole
run()again, along with whichever copy's bugs it happened to start from.
The pattern
Intent: define the skeleton of an algorithm in one method of a base class and defer some of its steps to subclasses, so subclasses can redefine those steps without changing the algorithm's structure.
- Abstract class (
Importer) - Holds the algorithm. It declares the steps and implements the ones that are the same for everyone. Nobody creates an
Importerdirectly. - Template method (
run) - The method that fixes the order of the steps:
parse, thenvalidate, thensave. It is concrete and meant to be left alone: subclasses inherit it and do not override it. - Abstract step (
parse) - A step with no default. Each subclass must write it. The GoF book calls these primitive operations.
- Hook (
validate) - A step with a default body that a subclass may override. Here the default rejects any code that is not positive. Some hooks do nothing by default; they are extension points. (Some write-ups, including Interfaces & Abstract Classes, call every overridable step a hook, abstract or not; the GoF book keeps the word for steps with a default.)
- Fixed step (
save) - A concrete step the subclasses cannot change. Making it
private(orfinal) keeps how rows are stored in one place. - Concrete class (
CsvImporter,JsonImporter) - Writes the abstract steps and overrides the hooks it needs. It never calls the template method's steps itself: the template calls it.
abstract class Importer {
constructor(private db: Db) {}
// Template method: subclasses must not override it.
run(text: string) {
const rows = this.parse(text);
if (!this.validate(rows)) {
return "rejected";
}
this.save(rows);
return `saved ${rows.length}`;
}
// Abstract step: each format must write it.
protected abstract parse(text: string): number[];
// Hook: a default rule that a subclass may override.
protected validate(rows: number[]) {
return rows.every((r) => r > 0);
}
// Fixed step: private, so no subclass can change it.
private save(rows: number[]) {
this.db.insert(rows);
}
}
class CsvImporter extends Importer {
protected parse(text: string) {
return text.split(",").map(Number);
}
}
class JsonImporter extends Importer {
protected parse(text: string) {
return JSON.parse(text);
}
// Overrides the hook: keeps the default, adds one rule.
protected validate(rows: number[]) {
return super.validate(rows) &&
new Set(rows).size === rows.length;
}
}| Kind of step | In Importer | A subclass | Use it for |
|---|---|---|---|
| Template method | run(), concrete, not to be overridden | Inherits it as is | The order of the steps |
| Abstract step | parse(), declared abstract | Must implement it | What has no sensible default |
| Hook | validate(), with a default body | May override it | Optional or usually-the-same behavior |
| Fixed step | save(), private | Cannot change it | What must be the same everywhere |
The Hollywood principle
"Don't call us, we'll call you." In everyday inheritance a subclass calls up into its parent with super. In Template Method the parent's run() calls down into the subclass's parse() at the moment it chooses, and the subclass never decides when it runs. This inversion of control is what Interfaces & Abstract Classes shows with a single abstract step (TextExporter.export() calling line()), and what Factory Method uses for one creation step. Template Method is the general form: a whole algorithm of steps, some required, some optional, some locked. It is also the usual line between a library and a framework: you call a library, but a framework owns the skeleton and calls the steps you supply, such as doGet() or componentDidMount().
What the visualizer shows
- Class diagram: the abstract
Importeron top with its four methods (parsein italics because it is abstract), the two subclasses below it, andDbto the right. Whenrun()callsparse(),Importer.parseturns violet (it only declares the step) andCsvImporter.parseturns amber (its code runs). When the defaultvalidate()runs,Importeris amber: the code that runs is the base class's. - Objects at runtime:
csv,jsonand the shareddb. Only one message ever goes todb, fromjson, anddb.rowsshows what was saved. - Sequence of calls: the client sends
run(...)once per importer; every other arrow is a self-call loop on the importer's own lifeline (parse,validate,super.validate,save). That picture is the Hollywood principle: the calls come from the skeleton, not from the client. - Before / With Template Method switches between the two copies and the pattern. Log imports applies the change request (record the raw text before parsing) to whichever version is shown, and the Change request panel beside the code counts what each version had to edit.
Walkthrough
- 1
Create the subclasses
The client creates
db, thencsvandjsonwith it. It never creates anImporter: the abstract class cannot be instantiated, and it holds only the shared algorithm. - 2
One call from the client
csv.run("1,,3").CsvImporterhas norun(), so the inheritedImporter.runlights up in amber: from here on, the base class is in charge. - 3
Call down to the abstract step
run()callsthis.parse(text).Importer.parseis only declared (violet), so dynamic dispatch runsCsvImporter.parse, which returns[1, 0, 3]: the blank cell became0. - 4
The hook runs its default
Next
run()callsthis.validate(rows).CsvImporterdoes not override it, so the default inImporterruns and returnsfalse. - 5
The skeleton stops
run()returns"rejected"andsave()is never reached.CsvImporternever wrote a check, yet it is protected by one, because the check is a step of the skeleton. - 6
Same skeleton, other subclass
json.run("[4,5]")runs the sameImporter.run. This timethisis aJsonImporter, so the call down lands inJsonImporter.parse, which returns[4, 5]. - 7
An override that extends the hook
JsonImporteroverridesvalidate(). Its override first callssuper.validate(rows), so the default rule runs inImporter, then adds its own rule (no duplicate codes). Both pass. - 8
The fixed step
run()calls its privatesave(), which callsdb.insert([4, 5]).db.rowsbecomes[4, 5]andrun()returns"saved 2". The closing note points at the sequence view: the client sent two messages, the skeleton sent all the others. - 9
Log imports (change request)
With Log imports applied,
Importergains alogfield and one first line inrun(). Bothcsv.logandjson.logfill up, and neither subclass was opened.
Before and after
Without the pattern
- Each importer holds a full copy of the algorithm
- The copies have drifted: CSV saves a blank cell as code
0 - Nothing forces every format to validate, or to validate before saving
- A change to the outline is made once per copy
- Each class reads top to bottom with no jumping around
With Template Method
- The algorithm is written once, in
Importer.run() - Every format validates, because validation is a step of the skeleton
- Subclasses write only what differs:
parse(), and a hook when needed - A change to the outline is one edit in the base class
- Reading one importer means reading the base class as well
| Change request: log every import | Before | With Template Method |
|---|---|---|
| Existing classes edited | 2 (CsvImporter, JsonImporter) | 1 (Importer) |
| New classes | 0 | 0 |
| Lines changed in existing classes | 4 (+4 −0) | 2 (+2 −0) |
The edit itself is identical: a log field and a this.log.push(text) line. Before, it has to be made in every copy, and the line count grows with the number of formats: with five importers it would be ten lines in five classes, and one forgotten copy is the same kind of drift that let the 0 in. With Template Method it is always one edit in one class, however many formats exist.
Variations
Making the template non-overridable
If a subclass overrides run() itself, the guarantee is gone. Languages differ in how they let you prevent that:
| Language | How to lock the template method |
|---|---|
| Java | Declare it public final String run(...). The compiler rejects any override. |
| C#, Kotlin | Methods are non-overridable unless marked virtual (C#) or open (Kotlin), so leave the template unmarked. C# also has sealed override. |
| C++ | Make the template a non-virtual public function that calls virtual steps (the Non-Virtual Interface idiom), or mark a virtual template final (C++11). |
| TypeScript | No final keyword. Teams rely on a doc comment and code review. The noImplicitOverride compiler option at least makes every override say override, so replacing run() cannot happen by accident. |
| Python | No enforcement at runtime. Decorate the method with typing.final (Python 3.8+) and a type checker such as mypy or Pyright reports overrides. |
Kinds of hooks
A hook can do nothing by default (beforeSave() as an empty method that a subclass may fill), compute a default (validate() here), or answer a yes/no question that switches an optional step on or off (shouldNotify() returning false by default, checked by the template before it sends a notification). Prefer a few well-named hooks over one per line of the template: each one is a promise to every future subclass.
abstract class Importer {
// constructor, db and save() as before
run(text: string) {
const rows = this.parse(text);
const ok = rows.every((r) => r > 0) && this.extraRules(rows);
if (!ok) return "rejected";
this.save(rows);
return `saved ${rows.length}`;
}
// Hook: no extra rules by default. Nothing to call super on.
protected extraRules(rows: number[]): boolean {
return true;
}
protected abstract parse(text: string): number[];
}
class JsonImporter extends Importer {
protected extraRules(rows: number[]) {
return new Set(rows).size === rows.length;
}
// parse() as before
}Passing the steps in as functions
The same skeleton can take its varying steps as arguments instead of from subclasses: importRows(text, parse, validate = positiveCodes). That trades inheritance for composition. Each call can mix any parser with any rule and swap them at runtime, which is Strategy applied to individual steps. Use subclasses when the steps belong together and form a named variant ("the CSV importer"); use functions when they vary independently or when a variant is a one-off.
In real code
| Where | Template (the fixed flow) | Steps you supply |
|---|---|---|
java.io.InputStream | read(byte[] b, int off, int len) is implemented by calling read() repeatedly | The abstract read() that returns one byte. Subclasses are encouraged to override the bulk method too, for speed |
java.util.AbstractList | iterator(), indexOf(), contains(), equals(), hashCode() and more, written in terms of two methods | get(int) and size() for a read-only list; set, add(int, E) and remove(int) to make it modifiable |
| Java servlets | HttpServlet.service() reads the request method and dispatches | doGet(), doPost() and so on: hooks whose defaults reply that the method is not supported |
| Test frameworks | JUnit and Python's unittest run each test as set up, run the test, tear down (JUnit 3 did it in one template method, TestCase.runBare()) | setUp() and tearDown() hooks (annotations such as @BeforeEach in JUnit 5), and the test bodies |
| React class components | React decides when to mount, render, update and unmount a component | Lifecycle methods such as render(), componentDidMount() and componentWillUnmount() that React calls |
Python socketserver | BaseRequestHandler calls setup(), then handle(), then finish() for each request | handle() for the real work, plus optional setup() and finish(). All three do nothing by default |
When to use it, and when not to
Reach for Template Method when
- Several classes run the same steps in the same order and differ in one or two of them
- The order or a step must be enforced for every variant (validation, auditing, cleanup)
- You are writing a framework or base class that others extend at named points
- The variants are fixed per class: a CSV importer is always a CSV importer
Prefer something else when
- The step must change at runtime, or steps vary independently: pass objects or functions (Strategy)
- The "algorithm" is one step: a single abstract method, or a function argument, is enough
- Subclasses keep needing to change the order or skip steps: the skeleton is the wrong abstraction
- Variants would need several base classes at once (most languages allow one superclass)
Template Method vs similar patterns
| Pattern | What varies | How the variant is chosen | Built with |
|---|---|---|---|
| Template Method | Some steps of a fixed algorithm | By picking a subclass, fixed for that object's lifetime | Inheritance: the base calls overridable steps on this |
| Strategy | A whole algorithm (or one step of it) | The client passes or swaps an object at runtime | Composition: the context holds an interface |
| Factory Method | Which class gets created | By a subclass overriding the creation step | Inheritance; usually one step inside a template method |
| Builder (with a Director) | The parts and representation of a product | The Director runs a fixed build sequence on whichever builder it is given | Composition: the sequence lives in the Director, the steps in a builder object |
| State | Behavior as the object's state changes | The states switch the current state as events happen | Composition: the context delegates to its current state object |
Implementation
The visualizer's scenario as a complete program with the change request applied: an abstract Importer whose run method logs the input, calls the abstract parse step, calls the validate hook and calls a fixed private save step. CsvImporter writes only parse; JsonImporter writes parse and extends the hook to reject duplicates. The template is locked with final in Java, kept non-virtual in C++, marked with typing.final in Python, and protected only by a comment in TypeScript. The Java and C++ versions parse the tiny JSON array by hand to stay dependency-free; real code would use a JSON library.
import json
from abc import ABC, abstractmethod
from typing import final
class Db:
def __init__(self) -> None:
self.rows: list[int] = []
def insert(self, rows: list[int]) -> None:
self.rows.extend(rows)
class Importer(ABC):
def __init__(self, db: Db) -> None:
self._db = db
self.log: list[str] = []
# The template method. @final is checked by mypy or Pyright,
# not at runtime.
@final
def run(self, text: str) -> str:
self.log.append(text)
rows = self.parse(text)
if not self.validate(rows):
return "rejected"
self._save(rows)
return f"saved {len(rows)}"
# Abstract step: every format must write it.
@abstractmethod
def parse(self, text: str) -> list[int]: ...
# Hook: a default rule that a subclass may override.
def validate(self, rows: list[int]) -> bool:
return all(r > 0 for r in rows)
# Fixed step: the leading underscore marks it internal.
def _save(self, rows: list[int]) -> None:
self._db.insert(rows)
class CsvImporter(Importer):
# A blank cell becomes 0, as in the TypeScript version.
def parse(self, text: str) -> list[int]:
return [int(c) if c.strip() else 0 for c in text.split(",")]
class JsonImporter(Importer):
def parse(self, text: str) -> list[int]:
return [int(x) for x in json.loads(text)]
# Keeps the default rule and adds one: no duplicate codes.
def validate(self, rows: list[int]) -> bool:
return super().validate(rows) and len(set(rows)) == len(rows)
db = Db()
csv = CsvImporter(db)
js = JsonImporter(db)
print(csv.run("1,,3")) # rejected (blank cell became 0)
print(csv.run("1,2,3")) # saved 3
print(js.run("[4,5]")) # saved 2
print(js.run("[6,6]")) # rejected (duplicate code)
print(db.rows) # [1, 2, 3, 4, 5]
print(csv.log) # ['1,,3', '1,2,3']Key takeaways
- Template Method puts an algorithm's outline in one base-class method and lets subclasses fill in steps; the order of the steps is fixed for every variant.
- Steps come in three kinds: abstract steps a subclass must write, hooks with a default it may override, and fixed steps it cannot touch. Choosing the kind of each step is the design work.
- The base class calls the subclass, not the other way round (the Hollywood principle). That is how frameworks hand control to your code.
- Changing the algorithm is one edit in the base class. In the visualizer's "Log imports" request: 1 class edited by 2 lines, against 2 classes and 4 lines when each importer had its own copy.
- Lock the template where the language allows it (
finalin Java, non-virtual in C++); in TypeScript and Python rely on conventions and type checkers. - It is inheritance, so the choice is fixed per subclass and the base class is fragile. When steps must vary at runtime or independently, use Strategy instead.
Common pitfalls
- Overriding the template method itself in a subclass, which silently removes the guarantee. Make it
finalor non-virtual where you can, and document it where you cannot. - Too many abstract steps: every subclass must then write all of them, even when most would be identical. Give steps a default (make them hooks) unless no default makes sense.
- Hooks that only work if the override calls
super. A subclass that forgets drops the base behavior without any error; keep must-run behavior in the template and offer an empty hook for the extra part. - Changing the order of steps or a hook's default in the base class without checking the subclasses, which all depend on both (the fragile base class problem).
- Using Template Method for behavior that must change at runtime. An object's class cannot change after it is created, so this needs composition.
Interview tips
- Define it in one sentence, then name the three kinds of steps (abstract, hook, fixed) and say which methods in your design are which. Mention how you would stop the template from being overridden in your language.
- Expect "Template Method or Strategy?". Answer inheritance versus composition: fixed when the object is created versus swappable at runtime, and the base class controlling the flow versus the context delegating to an object.
- Bring a framework example to show you recognize it in the wild:
HttpServlet.service()callingdoGet(),InputStreambuilding its bulkreadon the abstract single-byteread(), or test setup and teardown hooks.
Real-world applications
- Data import and ETL pipelines: read, parse, validate, transform, load, with format-specific parsing.
- Web frameworks dispatching requests to overridable handlers (
HttpServlet.doGet, Django class-based views). - Test runners calling setup, test and teardown in a fixed order.
- UI component lifecycles where the framework calls render and mount or unmount methods.
- Report and document generators with a fixed header, body and footer structure.
- Turn-based games where the turn sequence is fixed and each game supplies its own moves and win check.
Test yourself
In the importer example, why does CsvImporter reject "1,,3" even though it never wrote any validation code?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.