Template Method Pattern
Define the skeleton of an algorithm in an operation — defer some steps to subclasses.
📌 Key IdeaBase class defines `final` template method calling primitive operations (
abstract or hooks). Invariant sequence stays closed; steps open for subclasses. Common with Factory Method on same hierarchy.Visual
🏛 `final` orchestrates hooks
abstract class DataExporter {
final void export() { // template method
open();
writeRows(); // subclass
close();
}
}Hollywood principle — base calls subclasses at defined points.
When to Use
- Several variants share same control flow but differ in steps (ETL export, UI wizards).
- You want to lock ordering of operations but allow customisation.
- Framework hooks (
Servlet.servicetemplate, JUnit lifecycle).
When NOT to Use
- Algorithms diverge completely — Strategy composition clearer.
- Deep inheritance trees become fragile — favour composition.
Anti-Pattern (What NOT to Do)
Duplicate export pipelinesBadjava
void exportCsv(Data d) { open(); writeCsv(d); close(); }
void exportJson(Data d) { open(); writeJson(d); close(); }open/close duplicated; swap order risk.The Right Way
Template fixes sequence — subclasses fill hooksGoodjava
abstract class ExportJob {
final void run(Data d) {
open();
writeBody(d); // subclass
close();
}
protected abstract void writeBody(Data d);
}Hooks like
beforeWrite() default empty — optional override.Pros & Cons
👍 Pros
- Code reuse of invariant structure.
- Hooks (
doHook()default empty) optional extension points.
👎 Cons
- Inheritance coupling — subclass tied to base design.
- Harder to test pieces without subclassing.
Common Confusions Cleared Up
Template Method vs Strategy
Template Method uses inheritance — skeleton in superclass. Strategy uses composition — context delegates to injected strategy object.
Interview Q&A
Likely Follow-up Questions
- How does this pair with Factory Method in same class hierarchy?
Quick Cheat Sheet
IntentFixed algorithm outline; vary steps.
Mechanism
final template + hooks / abstract prims.vs StrategyInheritance vs composed strategy object.