Design Pattern 简明教程

Design Patterns - Template Pattern

在模板模式中,抽象类暴露出定义的方法/模板来执行其方法。它的子类可以根据需要覆盖方法实现,但调用必须按照抽象类定义的方式进行。此模式属于行为模式类别。

Implementation

我们将创建一个定义操作的抽象类 Game,并将其模板方法设置为 final,这样就无法覆盖它。Cricket 和 Football 是扩展 Game 并覆盖其方法的具体类。

我们的演示类 TemplatePatternDemo 将使用 Game 来演示模板模式的使用。

template pattern uml diagram

Step 1

创建带有 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 game
      startPlay();

      //end game
      endPlay();
   }
}

Step 2

创建一个扩展上述类的具体类。

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

使用 Game 的模板方法 play() 来展示一种定义好的比赛玩法。

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

验证输出。

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!