for example making coffee has the follwoing steps:
1- boil water, 2- brewCoffeeGrinds 3- pourInCup, 4- addSugarAndMilk.
making tea has the following steps:
1- boil water, 2- steepTeaBag, 3- pourInCup, 4- addlemon
ass you can see that the method can be abstracted in a template method
as you can see we defined the template method prepareRecipe() as final.
brew() method, represent brewCoffeeGrinds and steepTeaBag, is defined as abstract so it can be implemented by the subclass.
same for addCondiments
now you can implement the class like this
in addition in template method you can use something called hook methods
hook methods has an empty implementation in the base class, the subclass can decide if it wants to implement it or not
Hollyowood Principle: dont call me i will call you.
you can see it here in Template Method, the super class is calling the sub class when it needs anything.
Template Method vs Strategy Pattern
Notice the difference between Template Method and Strategy Pattern,
1- Strategy Pattern depends on composition, here we have inheritance
2- In Strategy Pattern you can change the algorithm on runtime
3- Template Method defines just the skeleton of the algorithm, Strategy Pattern is responsible for the algorithm itself.