美文网首页
模板方法模式(Template Method)

模板方法模式(Template Method)

作者: 森码 | 来源:发表于2018-08-02 21:45 被阅读19次
  1. 定义
    定义了一个算法的步骤,并允许子类别为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤。

  2. 类图


    Template Method.png
  3. 例子

 /**
  * An abstract class that is common to several games in
  * which players play against the others, but only one is
  * playing at a given time.
  */
 
 abstract class Game {
 
     private int playersCount;
 
     abstract void initializeGame();
 
     abstract void makePlay(int player);
 
     abstract boolean endOfGame();
 
     abstract void printWinner();
 
     /* A template method : */
     final void playOneGame(int playersCount) {
         this.playersCount = playersCount;
         initializeGame();
         int j = 0;
         while (!endOfGame()){
             makePlay(j);
             j = (j + 1) % playersCount;
         }
         printWinner();
     }
 }

//Now we can extend this class in order to implement actual games:

 class Monopoly extends Game {
 
     /* Implementation of necessary concrete methods */
 
     void initializeGame() {
         // ...
     }
 
     void makePlay(int player) {
         // ...
     }
 
     boolean endOfGame() {
         // ...
     }
 
     void printWinner() {
         // ...
     }
  
     /* Specific declarations for the Monopoly game. */
 
     // ...
 
 }

 class Chess extends Game {
 
     /* Implementation of necessary concrete methods */
 
     void initializeGame() {
         // ...
     }
 
     void makePlay(int player) {
         // ...
     }
 
     boolean endOfGame() {
         // ...
     }
 
     void printWinner() {
         // ...
     }
  
     /* Specific declarations for the chess game. */
 
     // ...
 
 }

 public class Player {
     public static void main(String[] args) {
         Game chessGame = new Chess();
         chessGame.initializeGame();
         chessGame.playOneGame(1); //call template method
     }
 }

补充

  • 最常见的模式之一。

相关文章

网友评论

      本文标题:模板方法模式(Template Method)

      本文链接:https://www.haomeiwen.com/subject/zszsvftx.html