Skip to main content

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 types

Method 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:
Multi-Format Data Processing
Input:
processors.csv.processData(['item1', 'item2', null, 'item3', ''])
Output:
Loaded 5 CSV records → Converted 3 records to CSV format → Saved CSV file with 3 records → Generated CSV summary report
Game AI Strategies
Input:
ais.aggressive.playTurn()
Output:
Quickly gathered minimum resources | Built barracks and weapon factories | Mass produced combat units | Scouts deployed to explore map | Launched full-scale attack on enemy
Cross-Format Document Generation
Input:
generators.html.generateDocument('Project Report', ['Introduction text', 'Main findings', 'Conclusions'])
Output:
<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

design patternssoftware architecturecode organizationobject-oriented programming

Complexity Analysis

Time:O(n) - depends on algorithm steps
Space:O(1) - no additional space overhead

Implementation

data-processing

Time: O(n) | Space: O(n)
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 !== '');
  }
}