Template Method Pattern
The Template Method Pattern is a behavioral design pattern that defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm without changing its structure.
1. The Core Concept
This pattern is all about code reuse and enforcing a specific structure. You have an algorithm that consists of several steps. Some steps are the same for everyone, while others vary.
- Abstract Class: Defines the
templateMethod(). This method contains the algorithm logic and calls primitive operations (abstract methods) or hooks. - Concrete Classes: Implement the abstract methods to provide specific behavior for those steps.
2. Analogy: Building a House
The process of building a standard house is generally the same:
- Build Foundation
- Build Walls
- Build Roof
- Install Windows
The Template is this 4-step process.
- Wooden House: Implements "Build Walls" using wood.
- Glass House: Implements "Build Walls" using glass.
The order of construction (Foundation -> Walls -> Roof) remains fixed in the template, but the details of how each step is done are left to the subclasses.
3. Example (TypeScript)
Let's create a data mining tool that can handle different file formats.
// The Abstract Class
abstract class DataMiner {
// The Template Method
// It is often 'final' so subclasses can't override the structure itself.
public mine(path: string): void {
this.openFile(path);
this.extractData();
this.parseData();
this.closeFile();
}
// Common step (implemented here)
protected openFile(path: string): void {
console.log(`Opening file: ${path}`);
}
// Abstract steps (must be implemented by subclasses)
protected abstract extractData(): void;
protected abstract parseData(): void;
// Common step (implemented here)
protected closeFile(): void {
console.log("Closing file.");
}
}
// Concrete Class 1
class CsvMiner extends DataMiner {
protected extractData(): void {
console.log("Extracting data from CSV...");
}
protected parseData(): void {
console.log("Parsing CSV data...");
}
}
// Concrete Class 2
class PdfMiner extends DataMiner {
protected extractData(): void {
console.log("Extracting data from PDF...");
}
protected parseData(): void {
console.log("Parsing PDF data...");
}
}
// Usage
console.log("--- CSV Miner ---");
const csv = new CsvMiner();
csv.mine("data.csv");
console.log("\n--- PDF Miner ---");
const pdf = new PdfMiner();
pdf.mine("report.pdf");
4. Hooks
A Hook is a method in the abstract class that has a default (often empty) implementation. Subclasses can override it, but they don't have to. This allows subclasses to "hook into" the algorithm at specific points.
abstract class ReportGenerator {
generate() {
this.collectData();
if (this.customerWantsImages()) { // Hook usage
this.addImages();
}
this.print();
}
// Hook with default implementation
protected customerWantsImages(): boolean {
return true;
}
// ... other methods
}
5. Pros and Cons
| Pros | Cons |
|---|---|
| Code Reuse: Pull common code into the superclass. | Rigidity: You are limited by the provided skeleton. |
| Enforcement: Ensures the algorithm follows a specific sequence. | Liskov Substitution: Subclasses might violate LSP by suppressing a default step in a way that changes the intended behavior. |
| Inversion of Control: The superclass calls the subclass methods (Hollywood Principle). | Maintenance: Maintaining the template method can be hard if the algorithm becomes complex. |
6. Template Method vs. Strategy
Both patterns are used to alter the behavior of an algorithm, but they do it in different ways.
| Feature | Template Method | Strategy |
|---|---|---|
| Mechanism | Inheritance (Class level) | Composition (Object level) |
| Structure | Defines the skeleton of the algorithm. Subclasses fill in the blanks. | Defines a family of algorithms. The context delegates to a strategy object. |
| Flexibility | Static. Behavior is determined at compile time (by subclassing). | Dynamic. Behavior can be switched at runtime (by swapping objects). |
| Coupling | Tightly coupled to the superclass. | Loosely coupled via an interface. |
programming/design-patterns programming/object-oriented-programming programming/strategy-pattern