Template Method Pattern Design Patterns in Java

Template method pattern is a way of defining an abstract class or structure to perform a particular operation that and can be adjusted as per user requirements. It is a form of a behavior pattern and basically implements a piece of pre-defined code for a certain functionality that can be called by the programmer as per his/her need. These methods are designed as just a shell of a method with enough flexibility to be able to fit in any program.

Certain steps or implementation of the Template are made in such a way that can be easily overridden by subclasses. Base Class declares the ‘place holders’ in the method and the Derived Class perform the implementation of these place holders. This pattern comes under behavior pattern category of 23 GoF Design Pattern.

Template Method Pattern

According to the Gang of Four:

Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

Implementation of Template Design Pattern

Template method is an implementation of the true essence of Object Oriented Programming’s concept of code reusing. This saves the time and energy of programmers to rewrite the extensive code of commonly used functionalities. There are basically two components of a code; variant part that can be changed according to the application being developed and the invariant part which remains same and can be re-used. The first step for building to identify these two components of the algorithm by the component designer.

Spring 5 Design Pattern Book

You could purchase my Spring 5 book that is with title name “Spring 5 Design Pattern“. This book is available on the Amazon and Packt publisher website. Learn various design patterns and best practices in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- “AUTHDIS40“.
Spring-5-Design-Pattern

The next step involves the implementation of these variant and invariant components. The implementation of invariant parts is done using abstract base classes and the invariant parts are implemented either as a default or are not implemented. The implementation of variant components consists of a number of ‘place holders’ which are used for customization by programmers using the template and are provided by the programmer or client’s derived class. The invariant component is implemented through the Base or Abstract Class which defines the structure of the algorithm and the variant components are implemented through the Concrete Class which employs the specific parts of Abstract Class during its operation.

The framework employs template methods to provide their operations. The invariant parts of the particular functionality are implemented and placeholders are defined as per the requirement of the clients. The framework acts as the main focus i.e. as the Abstract Class but the components dependent on the client’s requirements use ‘place holders’ and are part of Derived Class. The Base or Abstract Class is the main class and calls the Derived Class methods for any customization.

Template Method Design Pattern used in Applications

The template method pattern is used in programming languages to implement the most used functionalities or algorithms. The code is designed in such a way that the method can be used simply by providing parameters in place of ‘hooks’ or ‘place holders’. The subclasses can be derived from these Abstract Classes for implementing variable behavior. This avoids duplication of code where there are similar methods being used.

A simple example of template methods is square root function which can be used all kinds of programs or applications irrespective of the domain. Another example is a simple Abstract Class car which can further be customized as per requirement depending on the application without having to write the code from scratch.

Benefits of the Template Method Pattern

There are following lists the benefits of using the Template pattern:

  • It reduces the boilerplate codes in the application by reusing code.
  • This pattern creates a template or way to reuse multiple similar algorithms to perform some business requirements.

UML Class Diagram of Template Pattern

Let’s see the following UML diagram is showing the all components of Template design pattern:

Template Method Pattern
AbstractClass

  • Is an abstract class that contains a template method defining the skeleton of an algorithm.

ConcreteClass

  • It is a concrete subclasses of AbstractClass that implements the operations to carry out the algorithm-specific primitive steps.

Example of Template Method Pattern implementation

We are going to create a DataAccessObject abstract class defining operations with a template method run() set to be final so that it cannot be overridden. CategoriesDao and ProductsDao are concrete classes that extend DataAccessObject and override its methods select() and process(). And also I have created a TemplatePatternDemo class, it is our demo class, will use DataAccessObject to demonstrate use of template pattern.

Step 1 : Create an abstract class with a template method being final.
DataAccessObject.java

/**
 * 
 */
package com.doj.patterns.behavior.template;

import javax.sql.DataSource;

/**
 * @author Dinesh.Rajput
 *
 */
public abstract class DataAccessObject {
	
	protected String connectionString;
    protected DataSource dataSource;

    public void connect(){
    	System.out.println("Connecting Database using connection string");
    	// Make sure mdb is available to app
    	connectionString = "jdbc:mariadb://192.168.201.122:3310/dojdb";
    }

    public abstract void select();
    public abstract void process();

    public void disconnect(){
    	System.out.println("Disconnecting Database");
    	connectionString = "";
    }

    // The 'Template Method' 
    public final void run() {
    	connect();
    	select();
    	process();
    	disconnect();
    }
}

Step 2: Create concrete classes extending the above class.
CategoriesDao.java

/**
 * 
 */
package com.doj.patterns.behavior.template;

/**
 * @author Dinesh.Rajput
 *
 */
public class CategoriesDao extends DataAccessObject {

	@Override
	public void select() {
		//Select query and execute it
		System.out.println("---Select statement for categories---");
	}

	@Override
	public void process() {
		//Iterate the result set
		System.out.println("---Process the selected results set for products---");
	}

}

ProductsDao.java

/**
 * 
 */
package com.doj.patterns.behavior.template;

/**
 * @author Dinesh.Rajput
 *
 */
public class ProductsDao extends DataAccessObject {

	@Override
	public void select() {
		//Select query and execute it
		System.out.println("---Select statement for products---");
	}

	@Override
	public void process() {
		//Iterate the result set
		System.out.println("---Process the selected results set for products----");
	}

}

Step 3: Use the DataAccessObject’s template method run() to demonstrate a defined way of connecting and disconnecting database.
TemplatePatternDemo.java

/**
 * 
 */
package com.doj.patterns.behavior.template;

/**
 * @author Dinesh.Rajput
 *
 */
public class TemplatePatternDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		DataAccessObject daoCategories = new CategoriesDao();
		daoCategories.run();
		System.out.println();
		DataAccessObject daoProducts = new ProductsDao();
		daoProducts.run();
	}
}

Step 4: Let’s run this demo class and verify the output.

Connecting Database using connection string
---Select statement for categories---
---Process the selected results set for products---
Disconnecting Database

Connecting Database using connection string
---Select statement for products---
---Process the selected results set for products----
Disconnecting Database
Previous
Next