BehavioralTypeScriptverifiedVerified

Template Method Pattern in TypeScript

Defines the skeleton of an algorithm in a base class, deferring certain steps to subclasses without changing the algorithm's overall structure.

How to Implement the Template Method Pattern in TypeScript

1Step 1: Define the abstract template with hook methods

abstract class DataMiner {
  // Template method — defines the algorithm skeleton
  mine(source: string): string[] {
    const raw = this.extractData(source);
    const parsed = this.parseData(raw);
    const filtered = this.filterData(parsed);
    this.reportResults(filtered);
    return filtered;
  }

  protected abstract extractData(source: string): string;
  protected abstract parseData(raw: string): string[];

  // Hook — subclasses may override
  protected filterData(data: string[]): string[] {
    return data;
  }

  // Default implementation
  protected reportResults(data: string[]): void {
    console.log(`Mined ${data.length} records.`);
  }
}

2Step 2: Implement concrete miners that override steps

class CsvMiner extends DataMiner {
  protected extractData(source: string): string {
    return `CSV content of ${source}`;
  }

  protected parseData(raw: string): string[] {
    return raw.split("\n").filter(Boolean);
  }
}

class JsonMiner extends DataMiner {
  protected extractData(source: string): string {
    return `{"data": ["a","b","c"]}`;
  }

  protected parseData(raw: string): string[] {
    return JSON.parse(raw).data as string[];
  }

  protected filterData(data: string[]): string[] {
    return data.filter(item => item !== "b");
  }
}

3Step 3: Run the algorithm with different data sources

new CsvMiner().mine("report.csv");
new JsonMiner().mine("api/v1/data");

Template Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Template Method Pattern in the Real World

Consider a recipe for baking bread. The overall process—mix, knead, let rise, bake, cool—is fixed. But the specific flour blend, kneading technique, and baking temperature are decisions left to the baker. The cookbook provides the invariant sequence; individual bakers customize the steps that can vary without disrupting the overall process.