Template design pattern
Often times, we need to standardize an algorithm.
But this standardization is needed only at a high level. What does this mean? It means that the sequence of steps needs to stay the same. But different flavors of the algorithm can choose to alter the details of those steps, while keeping their sequence the same.
Usage in software engineering
Let’s take an example of writing test cases. In a project repository, we would have a base class for tests, from which all the test classes inherit. This base class will decide the exact sequence of steps- 1) setting up the testing environment, such as setting up a database 2) performing the tests 3) finally clearing the testing environments, such as dropping the database tables.
Note that the sequence of steps- setting up the environment, testing, and then clearing the environment is fixed. In addition, each of the steps is mandatory. But how exactly to perform each of the steps is of course dependent on the test subclasses that extend the base class for test.
The philosophy
Algorithms form the crux of business logic. While the steps and their sequence stay the same, the exact implementations of the steps might differ, depending on the variations of the same algorithm.
This is where the Template pattern comes into the picture. Not only does the base class dictate what should be the steps of the algorithm, it also dictates their sequence. The subclasses extending the base class then implement the exact details of the steps. The base class takes care of ‘what’ and ‘when’, while the subclasses take care of ‘how’.
For the purpose of this article, we will take a real life example of a Fitness centre. The fitness centre has several branches- each specializing in specific disciplines- such as yoga, weight training and boxing. While the workout sessions of these disciplines differ from one another, they are bound by few common principles- such as warning up before the sessions, and then cooling down after the sessions. The common principles, or rather the common sequence of steps, is what is represented by the FitnessCenter base class below, in its train() method.
The template method
public abstract class FitnessCenter {
public final void train(){
//declared final, because the sequence of activities stay fixed
warmUp();
physicalActivity();
coolDown();
getBonusPoint();
}//train
public void warmUp(){
System.out.println("Warming up");
}
public abstract void physicalActivity();
public void coolDown(){
System.out.println("Cooling down");
}
/*This is a hook. The subclasses can OPTIONALLY override it*/
public void getBonusPoint(){
System.out.println();
}
}//FitnessCenterNote that the methods warmUp(), physicalActivity(), coolDown() and getBonusPoint() are called from the function train(). The function train() is declared final. Why? This is because what steps to call, and in what order, is fixed, and we don’t want any of its subclasses to be able to change that.
Let’s look into the function definitions and declarations now.
warmUp() and coolDown() are definitions rather than declarations. This is because we want the subclasses to inherit the same definitions, or the same ways of warming up and cooling down. Of course the subclasses of FitnessCenter can override them if they wish.
What about the physicalActivity() method? It is declared abstract. That means the subclasses have to define them. This makes sense too. The physical activities- yoga, weight training and boxing are quite different from one another. Only the subclasses would know how to go about them, and so it is best for the base class FitnessCenter to leave the definitions of physicalActivity() to the individual subclasses.
Get Snigdha Sanat’s stories in your inbox
Join Medium for free to get updates from this writer.
In the Template design pattern of software engineering, the train() method is called the template method; and rightly so- as it defines the template of the algorithm. As we see, some of the methods, like warmUp() and coolDown(), are defined in the FitnessCenter class itself, and some of the methods, like the physicalActivity() method, is declared as abstract, and the subclasses define it. We see that in action below for the subclasses of FitnessCenter- YogaCenter, WeightTrainingCenter and BoxingCenter.
public class YogaCenter extends FitnessCenter {
@Override
public void physicalActivity() {
System.out.println("Yoga in progress");
}//physicalActivity
}//FitnessCenterpublic class WeightTrainingCenter extends FitnessCenter {
@Override
public void physicalActivity() {
System.out.println("Weight training in progress");
}//physicalActivity
@Override
public void getBonusPoint() {
//super.getBonusPoint();
System.out.println("You got bonus points in weight training");
System.out.println();
}
}public class BoxingCenter extends FitnessCenter {
@Override
public void physicalActivity() {
System.out.println("Boxing in progress");
}//physicalActivity
}The subclasses of FitnessCenter- YogaCenter, WeightTrainingCenter, and BoxingCenter define the physicalActivity() method, which was declared abstract in its base class.
Hooks
You might have noticed that we haven’t talked about the getBonusPoint() method yet. Is it different than the rest of the methods- warmUp(), physicalActivity() and coolDown()? In a way yes.
The hook is somewhat similar to the other methods which are defined in the base class, like warmUp() and coolDown(), in the sense that it is defined and not just declared like the physicalActivity(). But it also differs from warmUp() and coolDown() in that it does not do much in its definition. True, the template method train() does call it- but the hook does not do much. We can as well leave the definition of getBonusPoint() empty.
This means individual fitness centers for yoga, weight training and boxing can optionally override it with their own business logic, as does the WeightTrainingCenter subclass. And if not, it stays as defined in the base class definition.
We can have one or multiple hooks in a template method. Hooks represent an optional part of an algorithm. But notice a nuance here. The template method in the base class FitnessCenter- train() decides what and how many hooks to call, and when to call, even if the it leaves the hook definition(s) empty.
The subclasses can then optionally define these hooks, and they will get called at the points of the algorithm that the base class decided. Hooks are usually used for pre and post operations. In software engineering, if you are exposing your algorithms to multiple teams, you can choose to include hooks in your algorithm. The consuming teams can choose to optionally fill in the business logic of those hooks.
Definition
The template method in the Template design pattern defines the skeleton of an algorithm-deciding what steps to have, and when to have, thereby keeping the algorithm’s structure intact. But it lets its subclasses implement some of the steps.
This lets the base class have control over the structure of the algorithm, yet letting the subclasses easily add/change implementation details within the structure.
OO principle
The high level components decide which methods to be called for an algorithm, and when; the low level components only tune into the algorithm decided by the high level components and participate in the algorithm, adding the implementation details for the abstract methods of the base class, and optionally for the hooks. In that sense, the high level components(in this case the base class), call(technically dictate the behaviour of) the low level components(the subclasses), and not the other way round.
Code example
All the code examples are here.







