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.
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.
also read:
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.
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.
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.
There are following lists the benefits of using the Template pattern:
Let’s see the following UML diagram is showing the all components of Template design pattern:
AbstractClass
ConcreteClass
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.
/** * */ 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(); } }
/** * */ 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---"); } }
/** * */ 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----"); } }
/** * */ 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(); } }
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
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…