Template Method Pattern - Algorithm Skeletons in TypeScript

Learn the Template Method pattern for defining algorithm skeletons. TypeScript examples for data processing pipelines, testing frameworks, and build systems.

Behavioral

Detailed Explanation

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 overall structure. It is one of the fundamental techniques for code reuse via inheritance.

The Template

abstract class ReportGenerator {
  // Template method: defines the skeleton
  generate(): string {
    const data = this.fetchData();
    const processed = this.processData(data);
    const formatted = this.formatOutput(processed);
    return this.addHeader() + formatted + this.addFooter();
  }

  abstract fetchData(): Record<string, unknown>[];
  abstract processData(data: Record<string, unknown>[]): string;

  // Hooks: optional overrides
  formatOutput(content: string): string { return content; }
  addHeader(): string { return "--- Report ---\n"; }
  addFooter(): string { return "\n--- End ---"; }
}

Hooks vs Abstract Methods

  • Abstract methods (required): Subclasses MUST implement these.
  • Hook methods (optional): Have default implementations that subclasses CAN override.

Hollywood Principle

Template Method follows the "Hollywood Principle": "Don't call us, we'll call you." The base class controls the flow and calls subclass methods at the right time. Subclasses do not control when their methods are invoked.

Template Method vs Strategy

Both handle algorithm variation. Template Method uses inheritance (subclass overrides steps). Strategy uses composition (inject a strategy object). Strategy is more flexible because strategies can be swapped at runtime, while Template Method is fixed at compile time. However, Template Method is simpler when you only need to vary a few steps of a larger algorithm.

Real-World Examples

  • Testing frameworks: setUp(), runTest(), tearDown() follow the template method pattern.
  • React class components: componentDidMount, render, componentWillUnmount are hooks in a lifecycle template.
  • Build tools: Configure, compile, link steps in a build pipeline.

Use Case

Template Method is used in testing frameworks (setup-test-teardown lifecycle), data processing pipelines (extract-transform-load), document generators (header-content-footer), compiler phases (parse-analyze-generate), and web framework request handling lifecycles.

Try It — Design Pattern Reference

Open full tool