设计模式 - 模板模式



在模板模式中,抽象类公开定义好的方法/模板来执行其方法。其子类可以根据需要覆盖方法实现,但调用方式必须与抽象类定义的方式相同。此模式属于行为模式类别。

实现

我们将创建一个Game抽象类,定义具有模板方法的操作,并将模板方法设置为final,以便无法覆盖。CricketFootball是扩展Game并覆盖其方法的具体类。

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

Template Pattern UML Diagram

步骤1

创建一个具有最终模板方法的抽象类。

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();
   }
}

步骤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!");
   }
}

步骤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();		
   }
}

步骤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!
广告