Template Method
Fix the order of an algorithm's steps in a base class and let subclasses fill in individual steps.
The problem it solves
Two reports do the same job in the same order: print a header, then each item, then a footer. Only the formatting differs. If you copy the loop into both classes, every fix to the loop must be made twice. Sooner or later the copies drift apart.
Template Method puts the fixed order in the base class, in one method. The steps that vary are left as methods that subclasses fill in.
- The template method (
render) is the skeleton. It is written once. - Abstract steps must be implemented by every subclass.
- Hooks are optional steps with a default (often "do nothing"). A subclass overrides them only if it cares.
It is sometimes called the Hollywood principle: "don't call us, we'll call you". The subclass does not call the framework. The base class calls the subclass at the right moment.
1 of 7