模板方法模式

模板方法模式定義了一個算法的步驟,並允許子類別為一個或多個步驟提供其實踐方式。讓子類別在不改變算法架構的情況下,重新定義算法中的某些步驟。在軟體工程中,它是一種軟體設計模式,和C++模板沒有關連。

基本介紹

  • 中文名:模板方法模式
  • 外文名:Template method pattern
簡介,用法,用例(Java),

簡介

模板方法模式定義了一個算法的步驟,並允許子類別為一個或多個步驟提供其實踐方式。讓子類別在不改變算法架構的情況下,重新定義算法中的某些步驟。在軟體工程中,它是一種軟體設計模式,和C++模板沒有關連。

用法

模板方法模式多用在:
  • 某些類別的算法中,實做了相同的方法,造成程式碼的重複。
  • 控制子類別必須遵守的一些事項。
  • ...

用例(Java)

 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     } }

相關詞條

熱門詞條

聯絡我們