Arpit Mandliya

About Arpit Mandliya

I am java developer at Tata Consultancy Services Ltd. My current area of interest are J2EE,web development and java design patterns. I am technology enthusiast trying to explore new technologies. In spare time,I love blogging.

Template method design pattern in Java

Template method pattern is a behavioral design pattern which provide base method for algorithm,called template method which defers some of its steps to subclasses So algorithm structure is same but some of its steps can be redefined by subclasses according to context.

Template means Preset format like HTML templates which has fixed preset format.Similarly in template method pattern,we have a preset structure method called template method which consists of steps.This steps can be abstract method which will be implemented by its subclasses.
 
 
 
So in short you can say,In template method pattern,there is template method which defines set of steps and implementation of steps can be deferred to subclasses.Thus template method defines algorithm but exact steps can be defined in subclasses.

When to use it:

  • When you have a preset format or steps for algorithm but implementation of steps may vary.
  • When you want to avoid code duplication,implementing common code in base class and variation in subclass.

Structure:

So in above diagram,as you can see we have defined template method with three steps i.e. operation1,operation2 and operation3.Among them,opeation1 and operation2 are abstract steps,so these are implemented by ConcreteClass.We have implemented operation3 here.You can implement an operation in base class in two scenario first is if it is common to all and second is if it is default implementation of that method. UML diagram will be much clearer now.

Components:

AbstractClass

  • It defines template method defining the structure of algorithm.
  • It also defines abstract operations that will be implemented by subclasses to define steps of algorithm.

ConcreteClass

  • It implements abstract operation of super class to carry out subclass specific steps of the algorithm and also overrides operation if default behavior is not required

Important points about template method pattern:

  • Template method in super class follows “the Hollywood principle”: “Don’t call us, we’ll call you”. This refers to the fact that instead of calling the methods from base class in the subclasses, the methods from subclass are called in the template method from superclass.
  • Template method in super class should not be overriden so make it final
  • Customization hooks:Methods containing a default implementation that may be overidden in other classes are called hooks methods. Hook methods are intended to be overridden, concrete methods are not.So in this pattern,we can provide hooks methods.The problem is sometimes it becomes very hard to differentiate between hook methods and concrete methods.
  • Template methods are technique for code reuse because with this,you can figure out common behavior and defer specific behavior to subclasses.

Example:

Lets take example.When you have to read from two data source i.e CSV and database then you have to process that data and generate output as CSV files.Here three steps are involved.

  1. Read data from correspoding data source
  2. Process data
  3. Write output to CSV files

Java code:

Below class contains template method called ‘parseDataAndGenerateOutput’ which consists of steps for reading data,processing data and writing to csv file.

1.DataParser.java

package org.arpit.javapostsforlearning;

abstract public class DataParser {

    //Template method
    //This method defines a generic structure for parsing data
    public void parseDataAndGenerateOutput()
    {
        readData();
        processData();
        writeData();
    }
    //This methods will be implemented by its subclass
    abstract void readData();
    abstract void processData();

    //We have to write output in a CSV file so this step will be same for all subclasses
    public void writeData()
    {
        System.out.println('Output generated,writing to CSV');
    }
}

In below class,CSV specific steps are implement in this class

2.CSVDataParser.java

package org.arpit.javapostsforlearning;

public class CSVDataParser extends DataParser {

    void readData() {
        System.out.println('Reading data from csv file');
    }
    void processData() {
        System.out.println('Looping through loaded csv file');    
    }
}

In below class,database specific steps are implement in this class

3.DatabaseDataParser.java

package org.arpit.javapostsforlearning;

public class DatabaseDataParser extends DataParser {

    void readData() {
        System.out.println('Reading data from database');
    }

    void processData() {
        System.out.println('Looping through datasets');        
    }
}

4.TemplateMethodMain.java

package org.arpit.javapostsforlearning;

public class TemplateMethodMain {

    /**
     * @author arpit mandliya
     */
    public static void main(String[] args) {

        CSVDataParser csvDataParser=new CSVDataParser();
        csvDataParser.parseDataAndGenerateOutput();
        System.out.println('**********************');
        DatabaseDataParser databaseDataParser=new DatabaseDataParser();
        databaseDataParser.parseDataAndGenerateOutput();

    }

}

output:

Reading data from csv file
Looping through loaded csv file
Output generated,writing to CSV
**********************
Reading data from database
Looping through datasets
Output generated,writing to CSV

Used in java API:

Source code: Download
 

Reference: Template method design pattern in Java from our JCG partner Arpit Mandliya at the Java frameworks and design patterns for beginners blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

One Response to "Template method design pattern in Java"

  1. sanspriya84 says:

    Good example. Simple & crisp.

Leave a Reply


5 + = thirteen



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close