Template pattern
This is the 5th blog in the series of must-know design patterns in java. Today we will learn about template pattern.
Problem statement —
Implement a banking application that has support for multiple tasks such as Report generation, money transfer, analytics, etc. Before performing any task we should log the task and after performing we should make a book entry of the task.
The basic approach will be something like we create the task and have the object of required operations in each task.
Now, the problem with this approach is —
- We will have duplicate code inside all the tasks.
- There is no enforcement that the next time we create a task we will have to include logging and book entry.
- The system also violates open-closed principle as it’s not extensible every time we add a task we have modify the class to incorporate the changes.
How do we fix it?
We will use the template pattern to fix these issues as follow -
Now, we can create any number of tasks by extending this class, it enforces the logging and book entry for each task.
We can see that the enforcement of operations in each subtask also it makes the system scalable. Let’s see the operations that can be performed.
Result section —
The output will be —
Logging the task Report Generation
Performing generate report operation
Making book entry for Report Generation
Logging the task Money Transfer
Performing money transfer operation
Making book entry for Money Transfer
So we can see how easy is to implement the template pattern. Hope you have learned something today. Do clap 👏 and keep coding.
My previous design pattern blogs —