收藏
0有用+1
0

模板方法

计算机术语
模板方法模式定义了一个算法的步骤,并允许子类别为一个或多个步骤提供其实践方式。让子类别在不改变算法架构的情况下,重新定义算法中的某些步骤。在软件工程中,它是一种软件设计模式,和C++模板没有关连。
中文名
模板方法
性    质
一种设计模式
用    途
软件工程
学    科
计算机

用法

播报
编辑
模板方法模式多用在:
  • 某些类别的算法中,实做了相同的方法,造成程式码的重复。
  • 控制子类别必须遵守的一些事项。 [1]

用例(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用来交流设计模式的经验。 [2]