Template Method
Write the skeleton of an algorithm once in a base class, and let subclasses fill in only the steps that differ.
Description
The base class has one method, the template method (run()), that calls the steps in a fixed order: parse, validate, save. Some steps are abstract and every subclass must provide them; some are hooks with a sensible default that subclasses may override; some are shared and never change.
Each import format then only writes what's different, its parser and perhaps stricter validation, and the order of steps, the logging and the saving can't drift between formats. Frameworks use this constantly: lifecycle methods like setUp/tearDown in tests are hooks in someone else's template method.
Class diagram
Template Method pattern class diagram
- Abstract class CustomerImport with + run(raw): string, # parse(raw): Customer[], # isValid(c): boolean, # save(list): number.
- Class CsvImport with # parse(raw).
- Class JsonImport with # parse(raw), # isValid(c).
- CsvImport extends CustomerImport.
- JsonImport extends CustomerImport.
Sequence diagram
Template Method pattern sequence diagram
- Client → JsonImport: run(raw) (template method in base).
- JsonImport → JsonImport: parse(raw) (JsonImport).
- JsonImport → JsonImport: isValid(c) (JsonImport hook).
- JsonImport → JsonImport: save(valid) (shared, base).
- Client receives ""JSON: 2 read, 1 valid, 1 saved"" back from JsonImport.
TypeScript example
Customer imports that share one run() skeleton. CSV only writes its parser; JSON writes a parser and overrides the validation hook. Saving and the order of steps are shared.
// Template Method: every import follows the same steps; subclasses fill in
// only the steps that differ.
interface Customer {
email: string;
name: string;
}
abstract class CustomerImport {
// The template method: fixed order, not meant to be overridden
run(raw: string): string {
const records = this.parse(raw);
const valid = records.filter((r) => this.isValid(r));
const saved = this.save(valid);
return `${this.source}: ${records.length} read, ${valid.length} valid, ${saved} saved`;
}
protected abstract readonly source: string;
// Required step: each format parses differently
protected abstract parse(raw: string): Customer[];
// Hook with a default: subclasses may tighten it
protected isValid(c: Customer): boolean {
return c.email.includes("@");
}
// Shared step: identical for every format
protected save(customers: Customer[]): number {
return customers.length; // insert into the database (omitted)
}
}
class CsvImport extends CustomerImport {
protected readonly source = "CSV";
protected parse(raw: string): Customer[] {
return raw
.trim()
.split("\n")
.slice(1) // skip header
.map((line) => {
const [email, name] = line.split(",");
return { email, name };
});
}
}
class JsonImport extends CustomerImport {
protected readonly source = "JSON";
protected parse(raw: string): Customer[] {
return JSON.parse(raw) as Customer[];
}
// stricter validation for the partner feed
protected isValid(c: Customer): boolean {
return super.isValid(c) && c.name.trim().length > 0;
}
}
export function demo(): string[] {
const csv = "email,name\nsam@example.com,Sam\nnot-an-email,Kim\nalex@example.com,Alex";
const json = '[{"email":"robin@example.com","name":"Robin"},{"email":"x@example.com","name":" "}]';
return [new CsvImport().run(csv), new JsonImport().run(json)];
}When to use it
Use it when
- Several classes do the same job in the same order and differ only in a few steps.
- You want to guarantee the order of steps, so nobody forgets validation or skips logging.
- You're writing a framework or base class that others extend through well-defined hooks.
Avoid it when
- Only one step varies and you'd rather pass it in. Use Strategy or a function parameter; composition is more flexible than inheritance.
- Subclasses need to change the order of steps. Then the skeleton isn't really shared.
- The hierarchy would get deep. Inheritance chains with template methods at several levels are hard to follow.
Pitfalls
- Subclasses overriding the template method itself and breaking the guaranteed order. In TypeScript there's no
final, so document it clearly and keep it short. - Too many hooks, so the base class becomes a maze of optional overrides. Keep the number of steps small.
- Subclasses that depend on the base class's private details (the fragile base class problem). Give steps clear inputs and outputs.
Alternatives
Strategy
Choose it when you prefer composition: pass the varying step in as an object or function instead of subclassing.
Factory Method
Choose it when the only step that varies is which object gets created.
Pipeline of functions
Choose it when steps are independent transformations: save(validate(parse(raw))) composes without a class hierarchy.