Design Pattern

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“.

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:


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
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago