All you need to know about Template Method Design Pattern
Template method design pattern is a behavioural design pattern that is concerned with algorithms and the assignment of responsibilities between objects, as do all patterns that fall in this category. The speciality of behavioural design patterns is that they not only describe patterns of objects and classes but also the patterns of communication between them. You might have heard of encapsulating object creation, method invocation and other complex interfaces. What you might not have heard of is encapsulating algorithms. Template method design pattern is all about that. In this article, we will discuss what is Template method design pattern, why it is used, and a simple Template method design pattern java example to demonstrate its use case.
What is Template method design pattern?
Template method design pattern is a design pattern that provides an abstract definition of an algorithm with the help of an abstract method called Template Method. Like most of the behavioural design patterns, Template method design pattern uses inheritance to distribute behaviour between classes. In this pattern, each step invokes either an abstract or a primitive operation. A subclass provides additional details to the algorithm by defining the abstract operations. So, what is Template method design pattern’s intent? The intent is to define the skeleton of an algorithm by postponing some steps to subclasses i.e. it lets subclasses define certain steps of an algorithm in their own way keeping the structure of the algorithm intact.
Why do we need Template method design pattern?
Using design patterns such as the Template method design pattern, we can reduce redundancy in code. We will see an example of it soon. Template methods are the basic techniques of code reusability. If we are to design a framework or a library, there obviously will be common behaviour between classes that have similar structure and purpose and to deal with that we need a design pattern such as this one. In our case template methods are the means of factoring out common behaviour in library classes and frameworks. If you have ever used frameworks like angular, you have certainly come across injecting functions to controllers i.e. use them only when needed or “hook” them in and that will be called by angular itself. Such patterns lead to a principle that says, “Don’t call us we will call you”. Systems designed with such patterns allow low-level components to hook themselves into the system and the high-level components determine when and how they are needed. This refers to how a parent class calls the operations of a subclass and not the other way around.
Let us see an example of the Template method design pattern in java.
Template Method Design Pattern Java Example
We will make use of a very simple example of making mango and orange juices. The algorithms are straightforward and have been written as method calls in respective classes. First, we will do it the amateur way and then see how the template method can abstract out some of the algorithmic features from the intended classes.
1. The OrangeJuice Class
Fig- template method design pattern java example – Simple Orange Juice Class
As you can see there are five method calls in the prepareRecipe method that has the “algorithm” for preparing an orange juice.
2. The Mango Juice Class
Fig- template method design pattern java example – Simple Mango Juice Class
The mango juice class is very much similar with one extra method addMilk. As you can see both the classes of have similar structure and our code is quite redundant. The steps that are common are peeling, grinding, adding condiments and finally pouring them in a cup.
Finally let us put our code to test:
Fig- template method design pattern java example – Testing the prepareJuice method
All we did was call the prepareJuice method to follow steps in each class. However, this feels quite redundant as mentioned earlier. And what we would like to do is abstract out the commonality in a “template method” and make use of the template method design pattern. Let’s see what we can do.
Read aslo: "What is Adapter Design Pattern: A brief explanation"
First of all, let us factor out common steps in juice making.
- Peeling – Peel orange or mango
- addToGrinder – Add the peeled fruit to grinder
- addCondiments- add milk, sugar
- grind- grind the mixture
- Pour- pour it in a cup
We can implement these in an abstract template method.
- Abstract Juice Class
Fig- template method design pattern java example – Template Method
We have moved the common methods such as grind and pourInCup into the abstract class and factored out the methods that differ into abstract methods. For Example, peelFruit method will be re implemented by the mango juice accordingly.
Reworking the MangoJuice and OrangeJuice classes
Fig- template method design pattern java example – reducing redundancy
So, what have we achieved so far? As you can see the classes have only those methods that differ among them, others are in the template method (abstract juice class). So, creating an orange juice instance and calling prepare juice method will have the same effect (see the snippet below), the only difference is that the subclasses contain the implementation that differs, other all methods are provided by the template.
Fig- template method design pattern java example – Testing our simple design pattern
So, what was the point of doing all these? Template method design pattern is all about creating a template for an algorithm and nothing more than that. As we have seen a template is just a method that defines and algorithm. A few steps in the algorithm are defined abstract and are implemented by one or more subclasses. This way our algorithm’s structure remains the same while subclasses can provide their own version of implementation based on the template method.
Read also: "Decorator design pattern in java with examples"
The applicability of the Template method design pattern
The Template method design pattern should be used in cases where common behaviour among sub classes should be factored to avoid code duplication. First, we have to identify the differences in the existing code and then separate the differences into new operations. As we have done in our code example.
There are certain cases where the concept of hooks come which are basically operations that may be overridden by subclasses as opposed to abstract operations that must be overridden. A hook is a method that is given an empty or default operation. This allows us to have more control on the subclasses thereby permitting extensions only at certain points.
Last but obvious, Template method design pattern should be used to implement invariant parts of an algorithm once and defer behaviour that can vary to subclasses.
Basically, what you need to know about the template method is that it defines the steps of an algorithm. The subclasses implement those steps. This is the Template method design pattern in a nutshell. This design pattern is heavily used in the real world and you will see these specially in heavy frameworks and library classes. Similar to the Template method design pattern that define the behaviour of classes are command pattern, observer pattern, strategy pattern, etc. The basic purpose for all these design patterns is to enforce rules that make our code reusable and less redundant. Design principles like the Hollywood principle (“Don’t call us we will call you”) are commonly used while basing such patterns.
Read also: "Factory Design Patterns in Java"