Design Patterns - Template

design-patterns

Design Patterns - Behavioral - Template:

In Template pattern, an abstract class exposes defined way(s)/template(s) to 
execute its methods. Its subclasses can override the method implementation as 
per need but the invocation is to be in the same way as defined by an abstract 
class. This pattern comes under behavior pattern category.

We are going to create a Game abstract class defining operations with a 
template method set to be final so that it cannot be overridden. Cricket and 
Football are concrete classes that extend Game and override its methods.

// Step 1: Create an abstract class with a template method being final.
public abstract class Game {
   abstract void initialize();
   abstract void startPlay();
   abstract void endPlay();

   //template method
   public final void play(){

      //initialize the game
      initialize();

      //start game
      startPlay();

      //end game
      endPlay();
   }
}

// Step 2: Create concrete classes extending the above class.
public class Cricket extends Game {
   void endPlay() {
      System.out.println("Cricket Game Finished!");
   }
   void initialize() {
      System.out.println("Cricket Game Initialized! Start playing.");
   }
   void startPlay() {
      System.out.println("Cricket Game Started. Enjoy the game!");
   }
}

public class Football extends Game {
   void endPlay() {
      System.out.println("Football Game Finished!");
   }

   void initialize() {
      System.out.println("Football Game Initialized! Start playing.");
   }

   void startPlay() {
      System.out.println("Football Game Started. Enjoy the game!");
   }
}

// Step 3: Use the Game's template method play() to demonstrate a 
// defined way of playing game.
Game game = new Cricket();
game.play();
System.out.println();
game = new Football();
game.play();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License