Template Pattern- Deep Dive(Java)
Introduction
Template pattern is another behavioral design pattern which helps you to define a skeleton of steps to be performed for an algorithm. This pattern is mostly used where you see same steps being repeated and where template pattern comes to rescue to help you define loose coupling & single responsibility across your classes.
Problem Statement
Let’s take a simple use case where in you want to achieve below steps.
- Extract data from databases/files/cloud storages.
- Parse data according to your defined strategy.
- Generate report from the parsed data.
- Store reports again back to some data store.
As you can see above steps can be duplicated if we are trying to extract data from files/databases or any cloud storage.
If we follow template pattern, we will be able to structure our codebase and achieve loose coupling & srp, irrespective of any new storage which can get added in future.
Deep Dive
- Let’s try to define template for our steps which will involve an abstract class as shown below containing abstract steps which needs to implemented by concrete classes.

- Now building concrete classes would be piece of cake now . Here is our Database class which implements above methods as below.

Similarly, another class for file report generator is as follows

We are done now and looking at the below client call seems so simple and classy.

Take-Aways
- Your template method should be final so that implementing class can’t override and change the order of steps.
- You should mark all methods abstract which derived classes must implement.
Next time, while building a feature just think about steps being duplicated in your code and certain task is achieved via sequential steps. BOOM apply template and thank the creator later :) Happy Coding !