模板方法

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

基本介紹

  • 中文名:模板方法
  • 性質:一種設計模式
  • 用途:軟體工程
  • 學科:計算機
用法,用例(Java),設計模式,

用法

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

用例(Java)

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

設計模式

軟體工程中,設計模式(design pattern)是對軟體設計中普遍存在(反覆出現)的各種問題,所提出的解決方案。這個術語是由埃里希·伽瑪(Erich Gamma)等人在1990年代從建築設計領域引入到計算器科學的。
設計模式並不直接用來完成代碼的編寫,而是描述在各種不同情況下,要怎么解決問題的一種方案。面向對象設計模式通常以類別對象來描述其中的關係和相互作用,但不涉及用來完成應用程式的特定類別或對象。設計模式能使不穩定依賴於相對穩定、具體依賴於相對抽象,避免會引起麻煩的緊耦合,以增強軟體設計面對並適應變化的能力。
並非所有的軟體模式都是設計模式,設計模式特指軟體“設計”層次上的問題。還有其他非設計模式的模式,如架構模式。同時,算法不能算是一種設計模式,因為算法主要是用來解決計算上的問題,而非設計上的問題。
隨著軟體開發社群對設計模式的興趣日益增長,已經出版了一些相關的專著,定期召開相應的研討會,而且沃德·坎寧安(Ward Cunningham)為此發明了WikiWiki用來交流設計模式的經驗。

相關詞條

熱門詞條

聯絡我們