- Chapter
- Chapter 2 — Template Method
- Prerequisites
- Volume II (inheritance, LSP); Chapter 1 (Strategy)
- You will be able to
- Define an algorithm skeleton in a base class, separate fixed steps from required and optional steps, design hook methods deliberately, and protect the algorithm's order from subclasses
- Covers
- Algorithm skeleton; Hook methods
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Dynamic Dispatch From the Base Class
- 4A. Deep Dive — Protecting the Template
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
The Template Method pattern defines the skeleton of an algorithm in a method of a base class, deferring some steps to subclasses. Subclasses redefine certain steps without changing the algorithm's structure.

| Element | Role | Visibility |
|---|---|---|
| Template method | Defines the sequence of steps | public final |
| Concrete (fixed) steps | Implemented once in the base class | private or protected final |
| Primitive (abstract) operations | Steps subclasses must implement | protected abstract |
| Hook methods | Steps subclasses may override; default provided | protected |
2Why It Exists
Many processes share a stable order of steps with a few variable parts: importing files, handling HTTP requests, running batch jobs, executing tests. Without a template, each variant re-implements the whole process — including resource handling, error handling and logging — and they drift apart. Template Method writes the invariant parts once, enforces the order, and confines variation to clearly named steps. It is the classic form of code reuse through inheritance and the foundation of most object-oriented frameworks.
3Core Concepts
3.1 Algorithm skeleton
The skeleton is the template method: a fixed sequence of calls, some to concrete steps in the base class and some to abstract steps implemented by subclasses.

public abstract class DataImporter<R> {
public final ImportReport importFile(Path path) { // the template method
long start = System.nanoTime();
try (BufferedReader reader = open(path)) { // fixed
beforeParse(path); // hook
List<R> records = parse(reader); // abstract
List<Violation> violations = validate(records); // abstract
if (!violations.isEmpty() && !tolerateViolations()) { // hook
return ImportReport.rejected(path, violations);
}
int saved = save(records); // abstract
afterImport(path, saved); // hook
return ImportReport.ok(path, saved, violations,
Duration.ofNanos(System.nanoTime() - start));
} catch (IOException e) {
return ImportReport.failed(path, e); // fixed error handling
}
}
// ---- fixed step --------------------------------------------------------
private BufferedReader open(Path p) throws IOException {
return Files.newBufferedReader(p, StandardCharsets.UTF_8);
}
// ---- primitive operations: subclasses MUST implement ------------------
protected abstract List<R> parse(BufferedReader reader) throws IOException;
protected abstract List<Violation> validate(List<R> records);
protected abstract int save(List<R> records);
// ---- hooks: subclasses MAY override ------------------------------------
protected void beforeParse(Path path) { }
protected boolean tolerateViolations() { return false; }
protected void afterImport(Path path, int saved) { }
}A concrete importer supplies only what differs:
@Component
public final class CsvCustomerImporter extends DataImporter<CustomerRow> {
private final CustomerRepository customers;
public CsvCustomerImporter(CustomerRepository customers) {
this.customers = customers;
}
@Override
protected List<CustomerRow> parse(BufferedReader r) throws IOException {
return r.lines().skip(1).map(CustomerRow::fromCsv).toList();
}
@Override
protected List<Violation> validate(List<CustomerRow> rows) {
return rows.stream().filter(row -> !row.email().contains("@"))
.map(row -> new Violation(row.line(), "invalid email")).toList();
}
@Override
protected int save(List<CustomerRow> rows) {
var entities = rows.stream().map(CustomerRow::toCustomer).toList();
return customers.saveAll(entities).size();
}
}| What the skeleton guarantees | For every importer |
|---|---|
| Resources are always closed | try-with-resources in the template |
| Validation always happens before saving | Order fixed |
| Errors are reported uniformly | ImportReport built by the template |
| Timing is always measured | Fixed step |
3.2 Hook methods
A hook is a step with a default implementation — usually empty or returning a neutral value — that subclasses can override to plug into the algorithm at a defined moment.

| Hook type | Signature shape | Example use |
|---|---|---|
| Notification hook | void beforeX(), void afterX() | Logging, metrics, audit |
| Decision hook | boolean shouldX() | Skip a step, tolerate errors |
| Default-value hook | int batchSize() { return 500; } | Tuning per subclass |
| Transformation hook | R postProcess(R r) { return r; } | Adjust intermediate results |
@Component
public final class XmlOrderImporter extends DataImporter<OrderRow> {
// ... parse, validate, save ...
@Override protected boolean tolerateViolations() { return true; } // decision hook
@Override // notification hook
protected void afterImport(Path path, int saved) {
events.publishEvent(new OrdersImported(path.getFileName().toString(), saved));
}
}Guidelines for hooks:
- Name them after the moment (
beforeParse,onError) rather than the intended use. - Keep defaults safe — the algorithm must work if no hook is overridden.
- Document when they run and what state is available.
- Add hooks on demand, not speculatively — each is a permanent API.
4How It Works Internally — Dynamic Dispatch From the Base Class

1. The client calls the public, final template method on the concrete object (typed as the base class).
2. The template executes fixed steps directly.
3. Calls to abstract or hook methods are virtual calls resolved to the subclass's overrides.
4. Control always returns to the template, which decides the next step.
5. The subclass never calls the template's steps in a different order — it cannot, because the template is final.
This inverted control ("the base class calls the subclass") is known as the Hollywood Principle (Topic 2.2).
4ADeep Dive — Protecting the Template
Several Java features protect the skeleton from misuse:
| Risk | Protection |
|---|---|
| Subclass overrides the template and reorders steps | Declare the template final |
| Subclass overrides a fixed step | Make fixed steps private or final |
| Clients call steps directly, bypassing the template | Make steps protected, not public |
| Unknown subclasses in other modules | sealed base class with permits (or package-private constructor) |
Subclass calls super incorrectly | Avoid "call super" contracts; use hooks instead |
Avoid the "call super" anti-pattern. Designs that require overrides to call super.step() at the right moment are fragile: forgetting it silently breaks behaviour. Replace them with a final method that calls a hook:
// Fragile: subclasses must remember super.save()
protected int save(List<R> records) { audit(records); return 0; }
// Robust: template does the auditing, subclass fills a hook
private int saveAndAudit(List<R> records) {
int n = save(records); // abstract
audit(records, n); // fixed, cannot be forgotten
return n;
}Sealed templates. When all variants are known and owned by one team, a sealed base class documents and enforces the closed set:
public abstract sealed class DataImporter<R>
permits CsvCustomerImporter, XmlOrderImporter, JsonProductImporter { ... }5APIs / Features / Syntax
| Feature | Use in Template Method |
|---|---|
abstract class | Holds the skeleton and shared state |
final methods | Protect template and fixed steps |
protected abstract | Required steps |
protected with default body | Hooks |
Generics (DataImporter<R>) | Type-safe intermediate data per subclass |
sealed ... permits | Closed set of subclasses |
| Interfaces with default methods | Lightweight templates without state (Topic 2.3) |
6Practical Examples
6.1 A batch job template
public abstract class NightlyJob {
public final JobResult run(LocalDate businessDate) {
if (!shouldRun(businessDate)) return JobResult.skipped(); // hook
var lock = acquireLock(); // fixed
try {
var input = load(businessDate); // abstract
var output = process(input); // abstract
publish(output); // abstract
return JobResult.success(output.size());
} catch (RuntimeException e) {
onFailure(businessDate, e); // hook
return JobResult.failed(e);
} finally {
lock.release(); // fixed
}
}
protected boolean shouldRun(LocalDate d) { return !holidays.contains(d); }
protected void onFailure(LocalDate d, RuntimeException e) { }
protected abstract List<?> load(LocalDate d);
protected abstract List<?> process(List<?> in);
protected abstract void publish(List<?> out);
}6.2 Testing a subclass through the template
@Test
void rejectsFileWithInvalidEmails(@TempDir Path dir) throws IOException {
Path csv = Files.writeString(dir.resolve("c.csv"),
"name,email\nAsha,asha.example.com\n");
var report = new CsvCustomerImporter(repo).importFile(csv);
assertThat(report.status()).isEqualTo(Status.REJECTED);
verifyNoInteractions(repo); // save() never reached
}6.3 Testing the template itself
Create a minimal test subclass that records the order of calls — verifying that validation always precedes saving and hooks fire at the right moments.
7Common Problems & Mistakes
- Non-final template method — subclasses reorder or skip steps.
- Too many abstract steps — every subclass must implement boilerplate.
- Speculative hooks — dozens of empty methods nobody overrides.
- "Call super" requirements — fragile contracts.
- Public steps — clients bypass the template.
- Subclasses depending on base-class internals (protected mutable fields).
8Performance & Production Considerations
| Aspect | Guidance |
|---|---|
| Call overhead | Virtual calls to steps; negligible |
| Observability | Put timing, logging and metrics in fixed steps — uniform across subclasses |
| Error handling | Centralise in the template; subclasses throw domain exceptions |
| Resource management | Open/close in the template with try-with-resources |
| Transactions | Annotate the template carefully — proxies apply only to external calls (Volume III Topic 9.4) |
Because the template is the single path every subclass runs through, it is the right place for operational behaviour, and also a single point where a mistake affects every variant. Record a Micrometer timer and counters in the fixed steps, tagged with a job or importer name returned by a hook, so dashboards compare variants without each team instrumenting its own. Be careful with Spring proxies: @Transactional on a protected step that the template calls is ignored, because the call is a self-invocation that never passes through the proxy. Either make the public template method transactional, or move the transactional work to a separate bean or a TransactionTemplate. Keep slow I/O, such as reading a large file or calling a remote system, outside the database transaction, and put a correlation id into the logging context at the start of the template so every step's log lines can be traced together.
9Architecture & Design Considerations
- Template Method suits stable processes with few, well-defined variation points.
- Keep the base class small and focused on the process; put helpers elsewhere.
- Consider composition (Topic 2.3) when steps vary independently or at runtime.
- Document every protected method as part of the extension API.
10Interview Questions & Answers
What is the Template Method pattern?
Template Method is a behavioural pattern in which a base class defines the skeleton of an algorithm in one method and defers some steps to subclasses. The template method calls fixed steps implemented in the base class, abstract steps that every subclass must provide, and hooks that subclasses may override. Subclasses change what individual steps do but never the order in which they run. A DataImporter, for example, always opens the file, parses, validates, saves and reports, while CSV and XML subclasses supply only parsing, validation and persistence. It is reuse through inheritance with inverted control, the Hollywood Principle: the base class calls the subclass, not the other way round.
Why is the template method usually final?
Because the order of steps is the invariant the pattern exists to protect. If subclasses could override the template, one could skip validation, save before validating or forget to close resources, and the guarantees every caller relies on, such as uniform error handling, timing and auditing, would disappear without any compile error. Declaring it final makes the compiler enforce the skeleton: subclasses can change what a step does, never when it runs. The same reasoning applies to fixed steps, which should be private or final. If a subclass genuinely needs a different sequence, that is a signal that it is a different algorithm, or that composition would suit the problem better.
What is the difference between an abstract step and a hook?
An abstract step is a required part of the algorithm with no sensible default, so the base class declares it protected abstract and every subclass must implement it, such as parse or save in an importer. A hook is an optional extension point with a safe default implementation, usually an empty method or a neutral return value, which subclasses override only when they need to plug into a defined moment, such as beforeParse, or tolerateViolations returning false. The algorithm must work correctly when no hook is overridden. As a rule, add abstract steps only for genuine variation and add hooks only on demand, because each one becomes a permanent part of the extension API.
Give examples of hooks.
Hooks come in four common shapes. Notification hooks are void methods named after a moment, such as beforeParse(Path) or afterImport(Path, int), used for logging, metrics, auditing or publishing an event. Decision hooks return a boolean, such as shouldRun(LocalDate) to skip a job on holidays, or tolerateViolations() to continue despite validation errors. Default-value hooks supply tuning, for example an int batchSize() returning 500, which a high-volume importer overrides. Transformation hooks adjust intermediate results, such as R postProcess(R r) returning r unchanged by default. All of them have safe defaults, are protected rather than public, and should be documented with when they run and what state is available.
Why avoid "call super" contracts?
A call super contract requires every override to call super.step() at exactly the right point, which the compiler cannot check. A subclass that forgets the call, or calls it before rather than after its own work, silently breaks behaviour such as auditing, cache invalidation or resource release, and the bug often appears only in production. It also couples subclasses to the base class's implementation, which is the fragile base class problem. The robust alternative is to keep the mandatory work in a final or private method of the template that calls an abstract step or hook, for example saveAndAudit calling save and then audit. The required behaviour then cannot be forgotten.
How can you restrict which classes extend a template?
When all subclasses are known and owned by one team, declare the base class sealed with a permits clause, for example public abstract sealed class DataImporter permits CsvCustomerImporter, XmlOrderImporter, JsonProductImporter. Each permitted subclass must then be declared final, sealed or non-sealed, and must live in the same module, or in the same package when the code is in the unnamed module. The compiler rejects any other subclass. For older code, a package-private constructor restricts extension to the same package. Sealing documents the closed set, enables exhaustive pattern matching and lets the base class change its internals knowing exactly which subclasses must be checked.
What belongs in the template versus in subclasses?
The template owns everything that must be the same for every variant: the order of steps, resource acquisition and release with try-with-resources, locking, error handling and the shape of results, plus timing, metrics, logging and auditing. These are the guarantees callers and operators rely on, so they live in fixed private or final steps. Subclasses own only what genuinely differs, typically business-specific parsing, validation rules, transformation and persistence, plus optional reactions through hooks. If subclasses keep needing to change cross-cutting behaviour, or steps vary independently of each other, the design wants composition with Strategy objects instead. Keep the base class small and focused on the process itself.
How would you use Template Method in a batch platform used by many teams?
I would provide a final job template in a platform library that enforces the guarantees every team needs: a scheduling check such as shouldRun for business calendars, a distributed lock such as ShedLock so only one instance runs, consistent retries and failure handling, Micrometer metrics and tracing per run, and an audit record of inputs and outcomes. Teams implement a few small abstract steps such as load, process and publish, plus documented hooks like onFailure. I would keep the protected API minimal and versioned, test it with a recording subclass, and first consider Spring Batch, which already provides this skeleton with chunking and restartability, before building our own.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.