# Template Method
The **Template Method** pattern defines the *skeleton* of an algorithm in a base class — the fixed sequence of steps — while leaving some of those steps to be implemented (or overridden) by subclasses. The base class is the "template"; subclasses fill in the variable parts.
It's one of the original Gang of Four patterns and a textbook example of the [[Inversion of Control (IoC)]] principle: the base class controls *when* and *in what order* steps run. Subclasses don't drive the flow — they're called by the framework. This is the [[Inversion of Control (IoC)|Hollywood Principle]] in its purest object-oriented form.
## Structure
```
abstract class ReportGenerator {
// The template method: fixed skeleton, NOT overridden
final generate() {
fetchData() // primitive — overridden
transform() // primitive — overridden
render() // primitive — overridden
if (shouldEmail()) // hook — optional override
emailReport()
}
protected abstract fetchData()
protected abstract transform()
protected abstract render()
protected shouldEmail() { return false } // hook with default
}
class WeeklyReport extends ReportGenerator { /* implements primitives */ }
class MonthlyReport extends ReportGenerator { /* implements primitives */ }
```
The `generate()` method is the **template method** — typically `final` to prevent subclasses from changing the skeleton. The abstract methods are **primitive operations** that subclasses *must* provide. Optional **hook methods** have default behavior subclasses *may* override.
## Why it matters
- **Captures the invariant**: the order and structure of steps stay in one place, in the base class. You can't accidentally skip a step or run them out of order.
- **Reduces duplication**: the boilerplate around the variable parts (logging, error handling, transactions) lives once.
- **Makes extension explicit**: subclasses see precisely which extension points exist and what their contracts are.
## Template Method as IoC
The flow of control is *inverted* relative to procedural code. A caller invokes one method on the subclass; that method is implemented in the base class; the base class then calls back into the subclass for each variable step. The subclass code runs only when the framework calls it.
This is structurally identical to what frameworks like JUnit (calls your `@Test` methods inside its test-running skeleton) or HTTP middleware (calls your handler inside its request-lifecycle skeleton) do — they're Template Method scaled up to a framework.
## Template Method vs Strategy
Both vary parts of an algorithm. The crucial difference:
| | Template Method | [[Strategy Pattern]] |
|---|---|---|
| **Mechanism** | Inheritance — subclass overrides | Composition — pluggable object |
| **Binding** | Compile time, one variant per subclass | Runtime, swappable |
| **Granularity** | Multiple primitive steps in one algorithm | Whole algorithm replaced |
| **Best when** | Skeleton is fixed; few well-known variants | Algorithm itself varies; runtime choice |
[[Composition over Inheritance]] usually pushes you toward Strategy. Template Method earns its place when the skeleton genuinely is the invariant and the variation is fine-grained.
## Pitfalls
- **Inheritance lock-in**: subclasses can't easily change their parent at runtime. If variants need to be combined or swapped, Strategy fits better.
- **Fragile base class problem**: changes to the template method ripple through all subclasses; subclass authors may rely on undocumented invariants between primitives.
- **Subclass explosion**: if every combination of options requires a new subclass, you've hit a combinatorial limit — switch to Strategy or compose multiple small objects.
- **Liskov violations**: overrides that change preconditions or postconditions of primitives break correctness. See [[Liskov Substitution Principle (LSP)]].
## References
- Gang of Four — *Design Patterns: Elements of Reusable Object-Oriented Software* (1994), Template Method chapter
- Refactoring Guru — https://refactoring.guru/design-patterns/template-method
## Related
- [[Strategy Pattern]]
- [[Observer Pattern]]
- [[Inversion of Control (IoC)]]
- [[Composition over Inheritance]]
- [[Liskov Substitution Principle (LSP)]]
- [[Open Closed Principle (OCP)]]
- [[SOLID Principles]]