Template Pattern

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

Introduction

intent

The skeleton of an algorithm is defined in the parent class, and subclasses are allowed to redefine certain specific steps of the algorithm without changing the algorithm's structure.

Main problems solved

  • It solves the problem of repeatedly implementing the same methods in multiple subclasses by abstracting common methods into the parent class to avoid code duplication.

Use Case

  • When there are common methods that can be shared among multiple subclasses.

Implementation Approach

  • Define an abstract parent class: Contains the template method and some abstract or concrete methods.
  • Concrete Subclass: Inherits from the abstract parent class and implements abstract methods, without changing the algorithm structure.

Key code

  • Template Method: Defined in the abstract parent class, calls abstract methods and concrete methods.
  • Abstract method: Implemented by subclasses, representing the variable parts of the algorithm.
  • Concrete Method: Implemented in the abstract parent class, representing the invariant parts of the algorithm.

Application example

  • Construction Process: Steps such as foundation, wiring, and plumbing are the same, while later construction steps such as adding closets and fences are different.
  • The 81 tribulations of Journey to the West: The 81 tribulations set by the Bodhisattva represent a top-level logical skeleton.
  • Spring's support for Hibernate: Encapsulates common methods such as opening a transaction, getting a Session, and closing a Session.

Advantages

  • Encapsulate the invariant parts: The invariant part of the algorithm is encapsulated in the parent class.
  • Extend the variable parts: Subclasses can extend or modify the variable parts of the algorithm.
  • Extract common code: Reduces code duplication and facilitates maintenance.

Disadvantages

  • Increase in the number of classes: Each different implementation requires a subclass, which may cause the system to become large.

Usage suggestions

  • When multiple subclasses have common methods with identical logic, consider using the Template Method pattern.
  • For important or complex methods, you may consider defining them as template methods in the parent class.

Notes

  • To prevent malicious modification, the template method is usually declared final.finalKeyword modification to avoid being overridden by subclasses.

The main roles involved

  • Abstract parent class (Abstract Class):

    • Defines the template method and some abstract or concrete methods.
  • Concrete Classes:

    • Inherits from the abstract parent class and implements abstract methods.
  • Hook Method (optional):

    • Defined in the abstract parent class, can be overridden by subclasses to affect the behavior of the template method.
  • Client (optional):

    • Use abstract parent classes and concrete subclasses without needing to care about the details of the template method.

Implementation

We will create a class that defines operationsGameAbstract class, where the template method is set to final, so it will not be overridden.CricketandFootballExtendsGameThe concrete classes, which override the methods of the abstract class.

TemplatePatternDemo, and our demonstration class uses itGameto demonstrate the usage of the template pattern.

模板模式的 UML 图

Step 1

Create an abstract class whose template method is set to final.

Game.java

public abstract class Game { abstract void initialize(); abstract void startPlay(); abstract void endPlay(); //Templates public final void play(){ //Initialize game initialize(); //Start Game startPlay(); //End Game endPlay(); } }

Step 2

Create entity 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

UsageGameUse the template method play() to demonstrate how the game is defined.

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 and output the 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!
other extensions