模板方法模式

科技工作者之家 2020-11-17

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

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

用法模板方法模式多用在:

某些类别的算法中,实做了相同的方法,造成程式码的重复。

控制子类别必须遵守的一些事项。

...1

用例(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 } }本词条内容贡献者为:

李嘉骞 - 博士 - 同济大学

科技工作者之家

科技工作者之家APP是专注科技人才,知识分享与人才交流的服务平台。