Template Design Pattern

When do we need the template design pattern?

The template design pattern is useful when different components share some functionality and adding a change to one would need duplicate changes in the other component.

How do we implement the template design pattern?

The template design pattern is a behavioural design patter. In this, we have an abstract class that exposes templates in order of the subclasses to execute it. The subclasses can choose the override the existing implementation but the invocation needs to follow the same contract. 

Below is an example of the abstract class and it’s subclasses.

public abstract class Game {
   abstract void initialize();
   abstract void startPlay();
   abstract void endPlay();

   //template method
   public final void play(){
      initialize();
      startPlay();
      endPlay();
   }
}
public class TableTennis extends Game {

   @Override
   void endPlay() {
      System.out.println("Table tennis game is finished!");
   }

   @Override
   void initialize() {
      System.out.println("Initializing table tennis!");
   }

   @Override
   void startPlay() {
      System.out.println("Start playing table tennis!");
   }
}
public class Cricket extends Game {

   @Override
   void endPlay() {
      System.out.println("Cricket game finished!");
   }

   @Override
   void initialize() {
      System.out.println("Cricket Game Initialized!");
   }

   @Override
   void startPlay() {
      System.out.println("Cricket Game Started!");
   }
}

Do try out the example! Also, do note that the Factory pattern is a specialisation of template pattern 😀

No Comments

Post A Comment