Photo Courtesy Unsplash |
What is the Template Method Design Pattern?
The Template Method Design Pattern defines a sequence of steps of an algorithm and allows the subclasses to override the steps but do not allow to change the sequence. The Key to the Template Design Pattern is that we put the general logic in the abstract parent class and let the child classes define the specifics.
Template Method pattern falls under the behavioural design pattern, is one of the easiest to understand and implement. This design pattern is used popularly in framework development and also helps to avoid code duplication.
An abstract class contains the templateMethod which should be made final so that it cannot be overridden. This template method makes use of other operations available in order to run the algorithm but is decoupled for the actual implementation of these methods. Concrete class implements all the methods required by the templateMethod that were defined as abstract in the parent class.
Pattern Implementation
As am a coffee person, I will take an example of preparing the coffee using a template method pattern which should allow to understand the pattern easily instead of taking some framework implementations such as AbstractController, RequestProcessor, HttpServlet, InputStream, OutputStream etc.
protected boolean sugarFree = false;
public void prepareCoffee() {
boilWater();
addMilk();
if (!isSugarFree()) {
addSugar();
} else {
System.out.println("- No Sugar")
}
addCoffeePowder();
System.out.println("- Coffee is Ready!!!");
}
public final void boilWater() {
System.out.println("- Boiling Water");
}
public boolean isSugarFree() {
return sugarFree;
}
public void setSugarFree(boolean sugarFree) {
this.sugarFree = sugarFree;
}
abstract void addMilk();
abstract void addSugar();
abstract void addCoffeePowder();
}
Conclusion
- The pattern promotes the code reusability and decoupling, but at the expense of using inheritance.
- The pattern adhers to the Single Responsibility and Open/Closed principles of S.O.L.I.D - Design Principles.