What is the Template Method Design Pattern?

The template method design pattern allows you to define the steps of an algorithm within a single method of a class. This allows you to restrict certain operations of an application to a single method.


Each step of the algorithm that the template method defines is an inner method. However, the template method only handles the implementation of some of its inner methods. Subclasses typically implement one or more of the inner methods of the template method.

A subclass can implement an abstract method, but it cannot redefine the algorithm implemented by a final method.


How the template method works

A typical template method pattern has the following structure:

final void templateMethod() {
abstractOperation1();
abstractOperation2();

concreteOperation1();
concreteOperation2();

hook();
}

The first thing to note is that templateMethod() is final, so no subclass can override this method. The other important thing to note are the three types of methods that the template method pattern uses: concrete, abstract, and hook.

The abstract class that houses the template method implements all of its concrete methods, while concrete subclasses implement their abstract methods. The hook method normally does nothing by default, but a subclass has the ability to override these methods if needed.

Implementing the template method pattern in Java

The template method pattern acts as a framework for an application. So you’ll often see this pattern in software frameworks that provide the blueprint for application development.

For example, you can connect your application to one of many database systems. The steps to connect to and use a database follow a similar template:

public abstract class Database {
final void databaseTemplate() {
setDBDriver();
setCredentials();


connect();


createDB();
setData();
readData();


if (userWantsToUpdate()) {
updateData();
}

if (userWantsToDelete()) {
deleteData();
}


closeConnection();
}

abstract void setDBDriver();
abstract void setCredentials();
abstract void createDB();
abstract void setData();
abstract void readData();
abstract void updateData();
abstract void deleteData();

void connect() {
System.out.println("Connecting to database...");
}

void closeConnection() {
System.out.println("Destroying database connection...");
}

boolean userWantsToUpdate() {
return false;
}

boolean userWantsToDelete() {
return false;
}
}

This sample database class uses the template method pattern to create a template that you can use with any database. In order to use a database, your application must connect to it and destroy the connection after use. These activities are usually the same for all databases. Therefore, the abstract Database class can implement the associate() and close connection() methods.

The other methods in the template method differ depending on the database type. For example, a MySQL database stores data in tables, while a The MongoDB database stores data in collections. If you want to use one MySQL database in Javajust create a new MySQL class that extends the Database class:

public class MySQL extends Database {
@Override
void setDBDriver() {
System.out.println("Selecting MySQL driver...");
}

@Override
void setCredentials() {
System.out.println("Setting MySQL database Credential...");
}

@Override
void createDB() {
System.out.println("Creating a new table...");
}

@Override
void setData() {
System.out.println("Inserting data into database...");
}

@Override
void readData() {
System.out.println("Retrieving data from database...");
}

@Override
void updateData() {
System.out.println("Updating data in database...");
}

@Override
void deleteData() {
System.out.println("Deleting data from database...");
}
}

The MySQL class implements all of the abstract methods of the Database class. It can also override some concrete methods. However, it cannot be touched databaseTemplate() method that uses the final keyword.

public class Main {
public static void main(String[] args) {
Database mySQLDB = new MySQL();
mySQLDB.databaseTemplate();
}
}

This main class creates a new MySQL database object and uses the template method to simulate how an application would connect to the database. Executing the main method gives the following output on the console:

Template method for MySQL databases

You will notice in the output that the application never calls the update data() and Delete data() methods. That’s why the hook methods are important. In a SQL database, you may want to create new tables, insert data, and view your data. However, you may not want to update or delete data. Therefore, the hook methods give subclasses the ability to control these critical aspects of the algorithm.

@Override
boolean userWantsToUpdate() {
return true;
}

By simply adding the above code to the MySQL class, the application will now update the data in the database. Running the Main class again gives the following updated output:

Updated MySQL database template method

As you can see, the application is now updating the data in the database.

The benefits of using the template method design pattern

A key benefit of the template method pattern is that it encourages software reusability. This design pattern also supports efficient programming. A subclass need only implement methods that are unique to its operation.

In addition, an application using the template method pattern is more secure because external classes cannot change their operation structure.

Comments are closed.