Tuesday, November 21, 2017

Template method design pattern

This is another very important design pattern in Java and another core design pattern which is used in Spring framework.Template method design pattern is a behavioral design pattern. This is used to define a the flow of execution of the application.

Just think you need to build a building. Then you should begin it with foundation. You can't begin it with the roof. Likewise you can define the flow using this design pattern. 

Look at the following example. 


package com.app.designPatterns;

abstract class Building {

    abstract void makeFoundation();
    abstract void makeWalls();
    abstract void makeRoof();

    public final void build(){
        makeFoundation();
        makeWalls();
        makeRoof();
    }
}


class OfficeBuiding extends Building{

    @Override
    void makeFoundation() {
        System.out.println("Make foundation");
    }

    @Override
    void makeWalls() {
        System.out.println("Make walls");
    }

    @Override
    void makeRoof() {
        System.out.println("Make roof");
    }
}

public class TemplateDemo{

    public static void main(String args[]){
        Building building = new OfficeBuiding();
        building.build();
    }
}


Here you can see three classes. If you going to build a office building, it will be done in certain way. This flow cannot be changed. So if you want to create another building, you can do the same way. 

As you can see, the template method is final. That is why it cannot be changed. Look at the following class diagram for two buildings.


When it uses ?
  • javax.servlet.http.HttpServlet doGet() and doPost() methods.
  • In Spring framework - In Spring framework, it uses so many templates. These templates are created based on template method design pattern. 
  • All non abstract methods of followings
    1. java.io.InputStream
    2. java.io.OutputStream
    3. java.io.Reader
    4. java.io.Writer 
  • All non abstract methods in followings too.
    1. java.util.AbstractList
    2. java.util.AbstractSet
    3. java.util.AbstractMap
  • JDBC template uses this design pattern - In JDBC template we don't need to care about the open, close connections and so on. This is automatically done by the template itself. It executes the core workflow, we don't need to manage it.