The Template Method pattern encapsulates the invariant parts of an algorithm in a abstraction and allows concrete subclasses adjust the variant parts.
✅ Single Responsibility Principle (SRP)
✅ Open/Closed Principle (OCP)
✅ Liskov Substitution Principle (LSP) / Interface Segregation Principle (ISP)
✅ Dependency Inversion Principle (DIP)
// Primitive Operations
interface Operation {
startPlay(): void;
endPlay(): void;
}
// Abstract Template
abstract class Game implements Operation {
// Template method
// @final
public play(): void {
this.beforeStart(); // ← Hook method
this.startPlay();
this.endPlay();
}
// Primitive Operations
protected abstract startPlay(): void;
protected abstract endPlay(): void;
// Hook (Optional to override)
protected beforeStart(): void {
// default: do nothing
}
// Reusable Shared Logic
protected formatMessage(message: string): string {
const timestamp = new Date().toISOString();
return `[${timestamp}] ${message}`;
}
}
// Concrete Subclasses
class Football extends Game {
startPlay(): void {
console.log("Football Game Started!");
}
endPlay(): void {
console.log("Football Game Finished!");
}
}
// Client
const game: Game = new Football();
game.play();