Skip to content
BBaskaran

Template Method

Define an algorithm's skeleton and let subclasses override specific steps.

Use it when

Several classes share an algorithm's structure but differ in a few steps.

/**
 * Template Method: one export routine, with the format-specific steps left open.
 *
 * Real-world scenario: an admin page exports orders as CSV or JSON Lines. The
 * routine is always the same: announce the export, add a header if the format
 * has one, format each row, then add a summary line. That skeleton lives once in
 * the base class; each format only fills in the steps that differ.
 */

type Order = [id: string, customer: string, amount: number];

const ORDERS: Order[] = [
  ["ORD-1", "Asha", 49.99],
  ["ORD-2", "Ravi", 120.0],
];

abstract class OrderExporter {
  abstract readonly name: string;

  // Template method: fixes the order of the steps. Subclasses shouldn't
  // override it (TypeScript has no `final` keyword to enforce that).
  export(orders: Order[]): void {
    console.log(`--- ${this.name} export ---`);
    const header = this.header();
    if (header) {
      console.log(header);
    }
    for (const [id, customer, amount] of orders) {
      console.log(this.formatRow(id, customer, amount));
    }
    console.log(`(${orders.length} orders exported)`);
  }

  // Hook: optional step with a default that subclasses may override.
  protected header(): string | undefined {
    return undefined;
  }

  // Abstract step: every format must say how a row looks.
  protected abstract formatRow(id: string, customer: string, amount: number): string;
}

class CsvExporter extends OrderExporter {
  readonly name = "CSV";

  protected header(): string {
    return "order_id,customer,amount";
  }

  protected formatRow(id: string, customer: string, amount: number): string {
    return `${id},${customer},${amount.toFixed(2)}`;
  }
}

class JsonLinesExporter extends OrderExporter {
  readonly name = "JSON Lines"; // no header: keeps the default hook

  protected formatRow(id: string, customer: string, amount: number): string {
    return JSON.stringify({ id, customer, amount });
  }
}

function clientCode(): void {
  for (const exporter of [new CsvExporter(), new JsonLinesExporter()]) {
    exporter.export(ORDERS);
  }
}

clientCode();

// Output:
// --- CSV export ---
// order_id,customer,amount
// ORD-1,Asha,49.99
// ORD-2,Ravi,120.00
// (2 orders exported)
// --- JSON Lines export ---
// {"id":"ORD-1","customer":"Asha","amount":49.99}
// {"id":"ORD-2","customer":"Ravi","amount":120}
// (2 orders exported)

How it works

RoleClassesWhat it does
Abstract classOrderExporterexport() is the template method: it fixes the order of the steps
Stepsheader(), formatRow()header() is an optional hook with a default; formatRow() is abstract and must be implemented
Concrete classesCsvExporter, JsonLinesExporterFill in only the steps that differ for their format
ClientclientCode()Calls export() and gets the same routine in either format