template method pattern

Template Method Pattern

Template Method Pattern Definition

 
This pattern defines the skeleton of an algorithm in an operation, deferring some steps to subclasses. The
template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s
structure.[GoF definition]
 

Understanding Template Method Pattern

 
This pattern focuses on creating a template for an algorithm.

One or more steps is defined to be abstract and is implemented by the subclass.

This ensures the algorithm’s structure remains unchanged and subclasses can customize part of the implementation as per need. The below diagram explain the same.

 

template method pattern
 

Template Method Pattern Example

 

In this example, the prepare method provides the overall structure of the procedure for making beverage.

The brew() method is left as abstract so that subclasses can customize it.
 

package com.topjavatutorial.patterns.template;

public abstract class PrepareBeverage {
  public void prepare(){
    boilwater();
    brew();
    pourInCup();
  }
  
  public void pourInCup() {
    System.out.println("Pouring in cup");
  }
  
  abstract void brew();

  public void boilwater() {
    System.out.println("Boiling Water");
  }

}


 
MakeTea child class overrides the brew() method to provide custom implementation.
 
package com.topjavatutorial.patterns.template;

public class MakeTea extends PrepareBeverage {

  @Override
  void brew() {
    System.out.println("Steeping the Tea");
  }

}


 
MakeCoffee child class overrides the brew() method to provide custom implementation.
 
package com.topjavatutorial.patterns.template;

public class MakeCoffee extends PrepareBeverage {

  @Override
  void brew() {
    System.out.println("Dripping Coffee through Filter");
  }

}


 
package com.topjavatutorial.patterns.template;

public class TemplateDemo {

  public static void main(String[] args) {
    MakeTea tea = new MakeTea();
    MakeCoffee coffee = new MakeCoffee();
    
    System.out.println("\nMaking Tea...");
    tea.prepare();
    
    System.out.println("\nMaking Coffee...");
    coffee.prepare();
  }

}

 

Output

Making Tea…
Boiling Water
Steeping the Tea
Pouring in cup

Making Coffee…
Boiling Water
Dripping Coffee through Filter
Pouring in cup

 

Reference books

 
Head First Design Patterns

Head First Object-Oriented Analysis and Design

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags