模板方法模式(Template Method Pattern)

    在模板方法模式中,一个抽象类定义模板方法,然后以本身不可覆盖的方法中调用这些模板方法。实现类继承这个抽象类,覆盖原来需要重新定义业务逻辑的模板方法。这个模式属于行为型模式之一,也是比较常用的设计模式之一。

    实例实现,定义一个抽象类Game,分别定义其继承类Cricket和Football。UML类图如下所示:

 

 

定义游戏类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();
   }
}


具体实现类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!");
   }
}


测试类,测试运行结果。

public class TemplatePatternDemo {
   public static void main(String[] args) {
 
      Game game = new Cricket();
      game.play();
      System.out.println();
      game = new Football();
      game.play();             
   }
}

运行结果:

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!


    是不是觉得这里例子挺简单的,这个模式确实很简单。

你可能感兴趣的:(模板方法模式(Template Method Pattern))