Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / Java

Template Method Design Pattern in Java

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
25 Mar 2013CPOL3 min read 24.1K   13   3  
Template method design pattern in Java.

Introduction

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

Template means Preset format like HTML templates which have a fixed preset format. Similarly, in the template method pattern, we have a preset structure method called template method which consists of steps. These steps can be an abstract method which will be implemented by its subclasses.

So in short, you can say, in the template method pattern, there is a template method which defines a set of steps and the implementation of steps can be deferred to subclasses. Thus, a template method defines an algorithm but the exact steps can be defined in subclasses.

When To Use It

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

Structure

Image 1

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

Image 2

Components

AbstractClass

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

ConcreteClass

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

Important Points about Template Method Pattern

  • The template method in a 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 the base class in the subclasses, the methods from the subclass are called in the template method from the superclass.
  • Template method in the super class should not be overridden so make it final.
  • Customization hooks: Methods containing a default implementation that may be overridden in other classes are called hook methods. Hook methods are intended to be overridden, concrete methods are not. So in this pattern, we can provide hook methods. The problem is sometimes it becomes very hard to differentiate between hook methods and concrete methods.
  • Template methods are techniques for code reuse because with this, you can figure out a common behavior and defer specific behavior to subclasses.

Example

Let's take an example. When you have to read from two data sources, e.g., CSV and database, then you have to process that data and generate the output as CSV files. Here, three steps are involved.

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

Image 3

Java Code

The class below contains a template method called parseDataAndGenerateOutput which consists of steps for reading data, processing data, and writing to a CSV file.

1. DataParser.java
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 the below class, CSV specific steps are implemented in this class.

2. CSVDataParser.java
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 the below class, database specific steps are implemented.

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
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 the Java API

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
I am a java developer and blogger.Love to connect with people interested in java,programming or blogging.You can visit my blog at http://java2blog.com/

Comments and Discussions

 
-- There are no messages in this forum --