Easy Tutorial
❮ Prototype Pattern Filter Pattern ❯

Template Pattern

In the Template Pattern, an abstract class publicly defines the method/template for executing its methods. Its subclasses can override the method implementations as needed, but the invocation will be carried out in the way defined in the abstract class. This type of design pattern falls under the behavioral pattern category.

Introduction

Intent: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.

Main Solution: Some methods are common, but re-implemented in each subclass.

When to Use: When there are some general methods.

How to Solve: Abstract these common algorithms.

Key Code: Implemented in the abstract class, other steps are implemented in subclasses.

Application Examples: 1. In building a house, the foundation, wiring, and plumbing are the same, only the differences in the later stages of construction such as adding cabinets and fences.

  1. In the Journey to the West, the 81 trials set by the Bodhisattva are a top-level logical skeleton.
  2. In Spring's support for Hibernate, some predefined methods are encapsulated, such as starting a transaction, obtaining a Session, closing a Session, etc. Programmers do not rewrite those standardized codes and can directly save an entity.

Advantages: 1. Encapsulate the invariant parts, extend the variable parts.

  1. Extract common code for easier maintenance.
  2. Behavior is controlled by the parent class, implemented by subclasses.

Disadvantages: Each different implementation requires a subclass, increasing the number of classes and making the system more complex.

Usage Scenarios: 1. Methods common to multiple subclasses with the same logic.

  1. Important and complex methods can be considered as template methods.

Notes: To prevent malicious operations, template methods are generally marked with the final keyword.

Implementation

We will create an abstract class Game that defines operations, with the template method set as final to prevent it from being overridden. Cricket and Football are concrete classes that extend Game and override its methods.

TemplatePatternDemo, our demo class, uses Game to demonstrate the usage of the Template Pattern.

Step 1

Create an abstract class with the template method set as final.

Game.java

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

   // Template method
   public final void play(){

      // Initialize the game
      initialize();

      // Start the game
      startPlay();

      // End the game
      endPlay();
   }
}

Step 2

Create concrete classes that extend the above class.

Cricket.java

public class Cricket extends Game {

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

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

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

Football.java

public class Football extends Game {

   @Override
   void endPlay() {
      System.out.println("Football Game Finished!");
   }

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

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

Step 3

Use the template method play() of Game to demonstrate the definition of the game.

TemplatePatternDemo.java

public class TemplatePatternDemo {
   public static void main(String[] args) {

      Game game = new Cricket();
      game.play();
      System.out.println();
      game = new Football();
      game.play();      
   }
}

Step 4

Execute the program, output results:

Cricket Game Initialized! Start playing.
Cricket Game Started. Enjoy the game!
Cricket Game Finished!

Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!
❮ Prototype Pattern Filter Pattern ❯