
Before I explain what is the Template Method pattern and where we use it let us discuss what is a design pattern.
What are Design Patterns?
Design patterns are recommendations on how you should be writing your programs, how they should be structured to achieve optimal performance and scalability. In the most basic sense, if you follow those recommendations, your application will be more or less the industry standard.
Follow the right design patterns when needed, and get acknowledged by your supervisors.
What is the Template Method Pattern?
To better understand the pattern, let us take an example of a task manager application.
In the application let us assume we have classes such as ManageTask.java and GenerateReport.java, and an AuditModel.java class that simply records the username of the user who used those classes.
These classes would look like



What these classes simply do is that, any time its functions/methods are used, the username is recorded with the help of the Audit Model class.
The problem with this approach is that, for any new functionality that comes up, we will have to keep adding this block of code, in each new class.
private AuditModel auditModel;public ManageTask(AuditModel auditModel) { this.auditModel = auditModel;}
This causes repetition of code, and also may cause problems when a team member forgets to include the block of code, which will break the application in one way or another.
The template method is simply designing a skeleton which acts like the base class for every class that needs to have the same kinds of statements/functions run. This method can also be used to run a set of commands, every time a function from a class is used. Template Method is used to make sure that certain kinds of classes follow certain kinds of rules.
In this way, you simply extend you application and add new features without having to worry about basics being implemented or having unnecessary duplicate code.
To implement this pattern using Inheritance, we first create a base class, in this case the BaseTask.java class.

This is our Skeleton Base, which will be extended by any other task class in this scenario. As you can see, the onExecute method is abstract and protected. This makes sure that when the ManageTask or GenerateReport is used, only the execute method is accessible. Since the execute method is called, it makes sure that auditModel.audit(“username”) is run before handling the task itself.

Making use of this pattern greatly simplifies our code and also makes very efficient.

As you can see, the on execute method is not found from the caller function, and thus it makes sure that the required statements(recording username) in the classes are called properly.

The output of the code:

Thank you for reading!