Template Method Pattern
Define algorithm skeleton, let subclasses override specific steps
Pattern Overview
📋 Template Method Pattern
The Template Method Pattern defines the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm's structure.
Core Concepts
🔹 Template Method - Defines algorithm structure with method calls
🔹 Abstract Methods - Steps that must be implemented by subclasses
🔹 Hook Methods - Optional steps that subclasses can override
🔹 Concrete Methods - Shared implementation used by all subclasses
Real-World Applications
Data Processing - Load, validate, transform, save with different formats Game AI - Common turn structure with different strategies Document Generation - Header, content, footer with different formats Testing Frameworks - Setup, execute, teardown with different test typesMethod Types
Abstract Methods - Must be overridden (pure virtual functions) Hook Methods - Can be overridden (empty default implementation) Template Methods - Should not be overridden (final methods) Concrete Methods - Shared utilities (common implementation)Implementation Benefits
✅ Code reuse - Common algorithm structure shared across subclasses
✅ Consistent structure - All implementations follow same pattern
✅ Flexible customization - Override only the steps that differ
✅ Inversion of control - Framework calls subclass methods
Examples:
processors.csv.processData(['item1', 'item2', null, 'item3', ''])Loaded 5 CSV records → Converted 3 records to CSV format → Saved CSV file with 3 records → Generated CSV summary reportais.aggressive.playTurn()Quickly gathered minimum resources | Built barracks and weapon factories | Mass produced combat units | Scouts deployed to explore map | Launched full-scale attack on enemygenerators.html.generateDocument('Project Report', ['Introduction text', 'Main findings', 'Conclusions'])<html><head><title>Project Report</title></head><body><h1>Project Report</h1><p>Introduction text</p><p>Main findings</p><p>Conclusions</p>Generated on 2024-01-01T12:00:00.000Z<meta name="generator" content="HTMLGenerator" charset="utf-8"></body></html>Concepts
Complexity Analysis
Implementation
data-processing
abstract class DataProcessor {
processData(data: unknown[]): string {
const results = [];
results.push(this.loadData(data));
results.push(this.transformData(this.validateData(data)));
results.push(this.saveData(data));
return results.join(' → ');
}
protected abstract loadData(data: unknown[]): string;
protected abstract transformData(data: unknown[]): string;
protected abstract saveData(data: unknown[]): string;
protected validateData(data: unknown[]): unknown[] {
return data.filter(item => item != null && item !== '');
}
}