Template Method
Intent
Defines the skeleton of an algorithm in a base class and lets subclasses override specific steps.
Problem
CSV, PDF and DOC importers share 80% of their steps, duplicated three times.
Solution
Put the shared steps in a base method that calls abstract or hook steps overridden by subclasses.
Real-world analogy
Houses built from a standard plan: the builder follows the same steps, and each owner customises a few (windows, finishes).
Structure
Hover or tap a numbered role to highlight it in the diagram.
- 1AbstractClass — Abstract Class defines templateMethod(), which calls the steps in order. Steps are abstract or have defaults.
- 2ConcreteClass1 — Concrete Classes override steps, never the template method itself.
Code example
Applicability
Use Template Method when clients should extend only particular steps of an algorithm.
Use Template Method when several classes share almost identical algorithms.
Pros and cons
Pros
- Reuse of shared code
- Clients override only small parts
Cons
- Limited by the skeleton
- Can violate Liskov if subclasses suppress steps
Relations with other patterns
Check yourself
CSV, JSON and XML exporters all do open → write header → write rows → close; only formatting differs.
Saved in this browser only. Part of Behavioral patterns (0/11).