Template Method
Define the skeleton of an algorithm in a base class β lock down the structure, let subclasses fill in the specific steps.
Intent & Description
π― Intent
Enforce a consistent algorithm structure while letting subclasses customize individual steps without touching the overall flow.
π Context
You have a data mining pipeline, report generator, or multi-step workflow that always follows the same sequence (open β extract β parse β analyze β close) but with different implementations for each source (CSV vs. XML vs. PDF). Duplicating the structure in every subclass is fragile.
π‘ Solution
Define the overall algorithm sequence in a base class templateMethod(). Mark each customizable step as abstract or overridable. Subclasses override only the steps they care about; the skeleton stays fixed in the base class.
Real-world Use Case
Source
π TL;DR
Base class defines the sequence. Subclasses fill in the blanks. Skeleton never changes. Great for pipelines and frameworks. Subclasses are stuck with whatever order the base class defines.
Advantages
- Algorithm structure is defined once β subclasses only override what they need to.
- Duplicate scaffolding code gets pulled up into one place.
Disadvantages
- Subclasses are tightly coupled to the base class structure β changes to the skeleton ripple down.
class DataMiner {
mine(path) {
this.openFile(path);
this.extractData();
this.parseData();
this.closeFile();
}
openFile(path) { console.log(`Opening ${path}`); }
closeFile() { console.log("Closing file"); }
extractData() {} // Abstract
parseData() {} // Abstract
}