Design Patterns (GoF) (50 Qs)•Part 2: Behavioral Patterns & Communication (11 - 24)
What is the Template Method Pattern?
junior LevelCode ExampleComponentsBehavioral
In Simple Words: Defines the skeleton of an algorithm in an abstract base class, deferring some steps to subclasses without changing the algorithm's overall structure:
- Uses invariant steps and abstract hooks:
typescript
abstract class DataMiner {
// Template Method: Defines overall flow
public mine(path: string) {
const rawData = this.readFile(path);
const parsed = this.parseData(rawData); // Abstract step
this.saveToDatabase(parsed);
}
protected abstract parseData(raw: string): any;
private readFile(path: string) { /* file read */ }
private saveToDatabase(data: any) { /* save */ }
}