What is Template method pattern?
Template method pattern defines the skeleton of an algorithm in a method, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
When to use it?
- Use Template method pattern when you have classes that contains similar algorithms with minor differences.
Problem
Let's say we create classes represents animal behavior. Our first version of implementation is below:
Animal
Instead of definingdoDailyRoutinein subclasses, we define it in superclassAnimal. All animals exactly follow the order, that is,wakeUp,eat,sleep.eatmethod is declared as abstract because each animal eats different things.
additionalBehaviorhas empty body, so it does nothing. However, we can override the method in subclasses if some animal have unique behavior. This kind of method is called hook in Template method pattern.Animal subclasses
Although animal subclasses can't change algorithm structure, they can override some of the step methods used bydoDailyRoutine(). Also, they can optionally add additional behavior by overriding the hook method.
SOCIAL SHARE CARD GENERATOR