Template Method Pattern

Template Method pattern is a behavioural design pattern.

This pattern defines the steps of an algorithm and allows sub-classes to provide the implementation for one or more steps

It provides default implementation for one or more steps which are common for all or some of the subclasses

Template pattern defines the skeleton of an algorithm in a method,deferring some steps to subclasses.

Template pattern lets subclasses to redefine certain steps of an algorithm without changing the algorithm’s structure.

The main goal in this pattern is to create a template which can be used by subclasses.

Template is a method which defines steps of an algorithm.

Let’s understand Template Method pattern with below example


We know that placing an order in ecommerce website will have several steps

1) Add items to cart
2) Add delivery address
3) Provide payment details
4) Review order details
5) Confirm place order

We also know that, there could be different types of order

1) Regular order – Items delivered to customer
2) Store Pickup order – Customer picks up items from Store

Now most of the steps for both Order types are same and hence we can define a template for that and override specific methods in subclass

Let’s implement Template Method pattern


We can define one template method with the set of steps to be performed and make that method as final, So that every subclass can just follow it rather than overriding it.

Define common methods in the abstract class where we define template methods

Let subclass override specific methods

Step 1

Create an abstract class with template method

  1. package com.kb.template;
  2.  
  3. public abstract class PlaceOrderTemplate {
  4.    
  5.      public final void placeOrder(){
  6.          addToCart();
  7.          setDeliveryAddress();
  8.          setPaymentDetails();
  9.          reviewOrderDetails();
  10.          confirmOrder();
  11.          
  12.      }
  13.  
  14.  
  15.     public abstract void setDeliveryAddress();
  16.    
  17.     public abstract void setPaymentDetails();
  18.  
  19.     public final void addToCart() {
  20.         System.out.println("Items added to cart");
  21.        
  22.     }
  23.    
  24.     public final void reviewOrderDetails() {
  25.         System.out.println("Review the order details");
  26.        
  27.     }
  28.    
  29.     public final void confirmOrder() {
  30.         System.out.println("Place the order after reviewing");
  31.        
  32.     }
  33.  
  34. }
package com.kb.template;

public abstract class PlaceOrderTemplate {
	
	 public final void placeOrder(){
		 addToCart();
		 setDeliveryAddress();
		 setPaymentDetails();
		 reviewOrderDetails();
		 confirmOrder();
		 
	 }


	public abstract void setDeliveryAddress();
	
	public abstract void setPaymentDetails();

	public final void addToCart() {
		System.out.println("Items added to cart");
		
	}
	
	public final void reviewOrderDetails() {
		System.out.println("Review the order details");
		
	}
	
	public final void confirmOrder() {
		System.out.println("Place the order after reviewing");
		
	}

}

Step 2

Create a subclass for placing regular order and override specific methods

  1. package com.kb.template;
  2.  
  3. public class RegularOrder extends PlaceOrderTemplate{
  4.  
  5.     @Override
  6.     public void setDeliveryAddress() {
  7.         System.out.println("Select or add new delivery address of customer");
  8.        
  9.     }
  10.  
  11.     @Override
  12.     public void setPaymentDetails() {
  13.         System.out.println("Provide payment details like Net banking, credit card");
  14.        
  15.     }
  16.  
  17. }
package com.kb.template;

public class RegularOrder extends PlaceOrderTemplate{

	@Override
	public void setDeliveryAddress() {
		System.out.println("Select or add new delivery address of customer");
		
	}

	@Override
	public void setPaymentDetails() {
		System.out.println("Provide payment details like Net banking, credit card");
		
	}

}

Step 3

Create a subclass for placing store pickup order and override specific methods

  1. package com.kb.template;
  2.  
  3. public class StorePickupOrder extends PlaceOrderTemplate{
  4.  
  5.     @Override
  6.     public void setDeliveryAddress() {
  7.         System.out.println("Select nearest store for pickup");
  8.        
  9.     }
  10.  
  11.     @Override
  12.     public void setPaymentDetails() {
  13.         System.out.println("Pay at counter through cash/POS");
  14.        
  15.     }
  16.  
  17. }
package com.kb.template;

public class StorePickupOrder extends PlaceOrderTemplate{

	@Override
	public void setDeliveryAddress() {
		System.out.println("Select nearest store for pickup");
		
	}

	@Override
	public void setPaymentDetails() {
		System.out.println("Pay at counter through cash/POS");
		
	}

}

Step 4

Create a client class to test this pattern

  1. package com.kb.template;
  2.  
  3. public class TemplatePatternClient {
  4.  
  5.     public static void main(String[] args) {
  6.         System.out.println(" .........placing Regular order.........");
  7.         PlaceOrderTemplate regularOrder = new RegularOrder();
  8.         regularOrder.placeOrder();
  9.         System.out.println(" .........placing Store pickup order.........");
  10.         PlaceOrderTemplate storePickupOrder = new StorePickupOrder();
  11.         storePickupOrder.placeOrder();
  12.  
  13.     }
  14.  
  15. }
package com.kb.template;

public class TemplatePatternClient {

	public static void main(String[] args) {
		System.out.println(" .........placing Regular order.........");
		PlaceOrderTemplate regularOrder = new RegularOrder();
		regularOrder.placeOrder();
        System.out.println(" .........placing Store pickup order.........");
        PlaceOrderTemplate storePickupOrder = new StorePickupOrder();
        storePickupOrder.placeOrder();

	}

}


We can see that, for both types of order same steps have been followed using template method in the abstract class and overridden specific methods in subclass

Key points about Template method pattern


Define one template method in the abstract class and make it as final

This method should contain the list of steps to be followed by each subclass

Provide abstract methods for those methods which can have different implementations in subclass

Define the methods which can be common for all the sub-classes

Avoid duplication in the code, the general algorithm is implemented once in the abstract class along with method definition for generic functionality and specific methods are implemented in the subclasses.

This patterns let the subclasses implement specific behaviour (through method overriding)

About the Author

Karibasappa G C (KB)
Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on

Comment (10)

  1. Hello

    I really liked your blog.however in this post i would like to add something ,

    you have mentioned there that

    *How we create object in Java ?

    Yes using constructor , and we should not allow users to access constructor and execute it every time they try to. *

    I believe this statement is completely wrong. constructor is executed that does not mean object is created. object is create only using new operator and constructor is executed to initialize the instance variable.

    Kindly correct it.. 🙂

    thanks again.

    1. Karibasappa G C (KB)
      Karibasappa G C (KB)

      Thanks PushP for bringing this into discussion!!

      Let me try to make you understand the below line
      we should not allow users to access constructor and execute it every time they try to.

      If we are making someone to access constructor I mean execute constructor multiple times it just creates new object according to Java concept.

      How ?
      you know that constructors don’t have names right,so the only we to make the constructor execution is by creating an object using new.
      I agree that constructor execution and object creation are different activities but my point here is when you allow someone to execute the constructor multiple times, it means you are calling constructors multiple times because there is no other way to execute the constructors.
      Note:going through programmatically not through reflection and all.

      your opinion
      constructor is executed that does not mean object is created , object is created only using new operator and constructor is executed to initialize the instance variable

      my understanding on your opinion
      if I go by English i agree with this sentence , but going by Java concept i can not agree with this.
      Because when constructor is executed it means that you have called it using new class_name(), it means one object gets created in Java.
      I am not saying constructor execution and object creation are synonyms but what i am saying is they are mutually dependent.

      So my point here is simple,
      we should not allow users create object multiple times which is same as we should not allow users to execute the constructors multiple times.

      preventing constructor execution is same as not allowing someone to create an object.

      Happy to hear your inputs again and Thank you so much !!

  2. karibasappagc

    Hi Mani,,,

    I have added subscribe option on the right sidebar, you can subscribe there to receive the updates 🙂

    Thank you once again…and welcome for your comments always.

  3. karibasappagc

    Hi Mani, Its really very good notice…

    I forgot to add clone and also i didn’t add one more approach using ENUM.

    But Reflection you are right , i didnt notice this situation. but its good to cover that as well.

    so i will edit this post sometime to include all the above scenarios.

    Thanks a lot for reading , observing the things and suggesting.

    Keep Suggesting the posts during your free time 🙂 Thank you once again…

  4. Manikandan Jayaraman

    Good one, KB 🙂

    I can break your code using reflection though:
    ===
    // Access constructor using reflection
    Class clazz = FinalSingleton.class;
    Constructor cons = clazz.getDeclaredConstructor();
    cons.setAccessible(true);
    FinalSingleton instanceThree = cons.newInstance();
    instanceThree.setX(300);
    System.out.println(“instanceThree.getX() :: “+instanceThree.getX());
    ===

    the above creates a new instance.you can avoid that by changig your constructor
    ===
    private FinalSingleton() {

    //If-block needed to avoid creation of another object using reflection
    /*if (LazyLoadFinalSingleton.SINGLETONINSTANCE != null) {
    throw new IllegalStateException(“Inside FinalSingleton(): instance already created.”);
    }*/

    x = 100;
    System.out.println(“Constructor Called. Instance created.”);
    }
    ===

    Also good to override clone method and throw clone not supported exception. You will never know where the loop hole is. 🙂

Leave a Comment

  • You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre lang="" extra="">

    • Please answer this simple challenge to post your valuable comment *