- 中文名
- 模板方法
- 性 质
- 一种设计模式
- 用 途
- 软件工程
- 学 科
- 计算机
模板方法模式多用在:
- 某些类别的算法中,实做了相同的方法,造成程式码的重复。
- 控制子类别必须遵守的一些事项。 [1]
/** * 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年代从建筑设计领域引入到计算器科学的。
设计模式并不直接用来完成代码的编写,而是描述在各种不同情况下,要怎么解决问题的一种方案。面向对象设计模式通常以类别察她或对象来描述其中的关系和相互作用,但不涉及用来完成应用程序的特定类别或对象。设计模式能使不稳定依赖于相对稳定、具体依赖于相对抽象,避免会引起麻烦的紧耦合,以增强软件设计面对并适应变化的能力。
