Template Method Pattern Tutorial from Scratch (2026)
The Template Method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. It lets subclasses redefine certain steps without changing the algorithm's structure.
This pattern is fundamental to framework design, where the framework calls your code through hook methods. It promotes code reuse by extracting invariant parts of an algorithm into a base class.
Algorithm Skeleton and Hook Methods
The Template Method pattern uses an abstract base class that defines a templateMethod() which calls several primitive operations. Subclasses override these primitive operations to provide specific behavior while preserving the overall algorithm structure.
Hook methods are optional overridable methods that provide default behavior. They act as extension points, allowing subclasses to inject additional logic at specific points in the algorithm without changing the template.
// Abstract base class with template method
class DataProcessor {
// Template method - defines algorithm skeleton
process(data) {
const validated = this.validate(data);
const transformed = this.transform(validated);
const result = this.compute(transformed);
this.hookAfterCompute(result);
return result;
}
// Primitive operations (must override)
validate(data) {
throw new Error('validate() must be implemented');
}
transform(data) {
throw new Error('transform() must be implemented');
}
compute(data) {
throw new Error('compute() must be implemented');
}
// Hook method (optional override)
hookAfterCompute(result) {
// Default: do nothing
}
}
// Concrete subclass
class CSVProcessor extends DataProcessor {
validate(data) {
if (typeof data !== 'string') throw new Error('CSV data must be string');
const lines = data.trim().split('\n');
if (lines.length < 2) throw new Error('CSV must have header + data');
return lines;
}
transform(data) {
return data.map(line => line.split(',').map(s => s.trim()));
}
compute(data) {
const header = data[0];
const rows = data.slice(1);
return rows.map(row => {
const obj = {};
header.forEach((key, i) => obj[key] = row[i]);
return obj;
});
}
hookAfterCompute(result) {
console.log(`Processed ${result.length} records`);
}
}
// Use
const processor = new CSVProcessor();
const csv = 'name,age\nAlice,30\nBob,25';
const output = processor.process(csv);
console.log(output);
Inheritance and Framework Design with Template Method
Frameworks like Java's AbstractList, Servlet's doGet/doPost, and React's component lifecycle use Template Method extensively. The framework calls your overridden methods at specific points in the lifecycle, and you provide the custom behavior.
The Hollywood Principle — 'Don't call us, we'll call you' — is central to Template Method. The base class controls the algorithm flow and calls subclass methods as needed. This inversion of control is a hallmark of framework design.
// Framework-style base class
class Game {
// Template method - game loop
run() {
this.initialize();
while (!this.isGameOver()) {
this.processInput();
this.update();
this.render();
this.hookEveryFrame();
}
this.cleanup();
this.hookAfterGameOver();
}
initialize() { throw new Error('Override'); }
isGameOver() { throw new Error('Override'); }
processInput() { throw new Error('Override'); }
update() { throw new Error('Override'); }
render() { throw new Error('Override'); }
cleanup() {}
// Hooks
hookEveryFrame() {}
hookAfterGameOver() {}
}
class Chess extends Game {
constructor() {
super();
this.turns = 0;
}
initialize() {
this.board = this.createBoard();
console.log('Chess game started');
}
isGameOver() {
return this.turns >= 10; // simplified
}
processInput() {
console.log('Waiting for player move...');
}
update() {
this.turns++;
}
render() {
console.log(`Rendering turn ${this.turns}`);
}
hookEveryFrame() {
console.log(`Turn ${this.turns} of chess`);
}
createBoard() {
return Array(8).fill(null).map(() => Array(8).fill(null));
}
}
const game = new Chess();
game.run();
Frequently Asked Questions
What is the difference between Template Method and Strategy?
Template Method uses inheritance to vary parts of an algorithm, with the base class controlling the flow. Strategy uses composition to make entire algorithms interchangeable. Template Method is for fixed skeletons with variable steps; Strategy is for completely swappable algorithms.
What are hook methods and why are they useful?
Hook methods are optional overridable methods in the template that do nothing by default. They provide extension points for subclasses to add behavior at specific steps without overriding the template method itself. This keeps the algorithm structure intact while allowing customization.
How does Template Method support the Hollywood Principle?
The Hollywood Principle says 'Don't call us, we'll call you.' The base class template method calls subclass implementations, not the other way around. This inversion of control means subclasses don't call the framework; the framework calls subclasses at defined extension points.
What are the downsides of Template Method?
Template Method relies on inheritance, which can lead to deep class hierarchies that are hard to maintain. Each subclass must implement primitive operations correctly, and the template method can become rigid if the algorithm skeleton needs to change. Prefer composition over inheritance where possible.
Originally published on Ayodhyyya. Last updated June 1, 2026.