design patterns ·
Template Method
Defines the skeleton of an algorithm in a base class, deferring specific steps to subclasses.
Theory
Explanation
Intuition first, formal definition second. Skim the bullets if you already know this; read the prose if you don't.
When multiple classes share the same algorithm structure but differ in specific steps, pull the common structure into a base class template method. Subclasses override only the varying steps.
The template method is declared final (or non-overridable) in the abstract base class. It calls abstract hook methods at appropriate points. Subclasses implement the hooks. The overall algorithm structure is fixed.
When to use
Data parsing pipelines, report generation, game loops, build processes, testing frameworks - any workflow with fixed overall structure but variable steps.
When not to
When you need runtime algorithm switching - use Strategy. When the varying steps are too different - the base class becomes incoherent.
Key insights
- Template Method is compile-time flexibility via inheritance; Strategy is runtime flexibility via composition
- Hook methods can have default implementations - subclasses may override but do not have to
- The Hollywood Principle: the base class calls subclass methods, not the other way around
- JUnit setUp/tearDown are Template Method hooks called by the test framework