← Back to Home

Template Method Pattern

Defines the skeleton of an algorithm in the base class and lets subclasses override specific steps.

What is it?

The Template Method pattern lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Example

abstract class DataProcessor {
  process(): string[] {
    const steps: string[] = [];
    steps.push(this.readData());
    steps.push(this.transformData());
    steps.push(this.saveData());
    return steps;
  }

  protected abstract readData(): string;
  protected abstract transformData(): string;
  protected abstract saveData(): string;
}

class CSVProcessor extends DataProcessor {
  protected readData(): string {
    return 'Reading CSV data...';
  }
  protected transformData(): string {
    return 'Converting CSV rows to objects...';
  }
  protected saveData(): string {
    return 'Saving objects to DB...';
  }
}

class JSONProcessor extends DataProcessor {
  protected readData(): string {
    return 'Reading JSON file...';
  }
  protected transformData(): string {
    return 'Parsing JSON to object...';
  }
  protected saveData(): string {
    return 'Inserting object to DB...';
  }
}

const processor = new CSVProcessor();
console.log(processor.process());

Common Uses

  • Framework lifecycle methods (e.g., React hooks, Angular lifecycle)
  • Form validation pipelines
  • Workflow steps where base structure is fixed

When to Use

  • You want to enforce a strict sequence of steps
  • Subclasses share structure but vary in detail

Caution

  • Harder to follow logic when too many layers inherit from the base
  • Inflexible if steps are not actually reusable