patterntypescriptTip
Template Method Pattern: Define an Algorithm Skeleton With Overridable Steps
Viewed 0 times
template methodbehavioral patternalgorithm skeletonhooksinvariant algorithmabstract steps
Problem
Multiple classes share the same algorithm structure but differ in specific steps. Duplicating the overall algorithm across subclasses leads to copy-paste bugs when the structure changes.
Solution
Define the invariant algorithm skeleton in a base class method. Mark the variant steps as
protected abstract methods that subclasses must implement.abstract class DataMigration {
// Template method — defines the skeleton
run(): void {
this.connect();
const data = this.extract();
const transformed = this.transform(data);
this.load(transformed);
this.disconnect();
}
protected abstract connect(): void;
protected abstract extract(): unknown[];
protected abstract transform(data: unknown[]): unknown[];
protected abstract load(data: unknown[]): void;
// Hook with default (optional override)
protected disconnect(): void { /* default no-op */ }
}
class PostgresMigration extends DataMigration {
protected connect() { console.log('connect to postgres'); }
protected extract() { return [/* query rows */]; }
protected transform(data: unknown[]) { return data.map(/* map */); }
protected load(data: unknown[]) { /* insert rows */ }
}Why
The template method inverts control: the framework (base class) calls the specific steps (subclass), not the other way. It eliminates duplicate algorithm structure while allowing variation in steps.
Gotchas
- Template method requires inheritance which reduces flexibility. Prefer composition with callbacks/strategies when the relationship is not a true 'is-a'.
- Hooks (optional override steps with default behavior) should be clearly documented — it is easy to miss that a step can be overridden.
- Avoid calling abstract methods from the constructor — the subclass may not have initialized its state yet.
Revisions (0)
No revisions yet.