Design Patterns - SPLessons

Template Pattern

Chapter 27

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Template Pattern

Template Pattern

shape Description

Template Pattern is a Behavioral Pattern that contains template methods for storing the algorithm steps. These algorithm steps are divided into sub classes. This method uses abstract methods for implementation. Template pattern is referred as “The Hollywood Principle” and the sub classes of the template can be overridden using final keyword.

shape Advantages

  • The logic of the system can be modified easily.
  • Template methods can be represented using customized hooks.
  • Algorithm steps can be kept in sub classes.

shape Conceptual
figure

shape Examples

Creating an abstract class Sports and making it as abstract.

public abstract class Sports 
{
   abstract void initialize();
   abstract void sPlay();
   abstract void ePlay();
   //template method
   public final void play()
{
      //initialize the game
      initialize();
      //start game
      sPlay();
      //end game
      ePlay();
   }
}

Creating a class Hockey and extending the class Sports.

public class Hockey extends Sports 
{
   void ePlay()//overrides the class method
 {
      System.out.println("Hockey Game Finished!");
   }   
   void initialize()//overrides the class method
 {
      System.out.println("Hockey Game Initialized! Start playing.");
   }   
   void sPlay()//overrides the class method
 {
      System.out.println("Hockey Game Started. Enjoy the game!");
   }
}

Creating a Tennis class and extending the class Sports.

public class Tennis extends Sports 
{  
   void ePlay()//overrides the class method 
{
      System.out.println("Tennis Game Finished!");
   }
   void initialize()//overrides the class method 
{
      System.out.println("Tennis Game Initialized! Start playing.");
   }
   void sPlay()//overrides the class method
{
      System.out.println("Tennis Game Started. Enjoy the game!");
   }
}

Creating a TemplatePattern class.

public class TemplatePattern 
{
   public static void main(String[] args) 
{
      Sports game = new Hockey();//creating object for Sports class
      game.play();
      System.out.println();
      game = new Tennis();
      game.play();		
   }
}

shape Output

The result will be as follows.

Hockey Game Initialized! Start playing.
Hockey Game Started. Enjoy the game!
Hockey Game Finished!
Tennis Game Initialized! Start playing.
Tennis Game Started. Enjoy the game!
Tennis Game Finished!

Summary

shape Key Points

  • Template Pattern – Default implementation can be provided.
  • Template Pattern – Algorithms can be easily implemented.