模板方法
模板方法模型是一种行为设计模型和设计模式。模板方法(template method)是一个定义在父类的方法,负责处理流程、算法的不变部分。模板方法会调用多个定义在父类的其他工具方法(helper method),而这些方法是算法的可变部分,有可能只是抽象方法并没有实现。模板方法仅决定这些抽象方法的执行顺序,这些抽象方法由子类负责实现,并且子类不允许覆盖模板方法(即不能重写处理流程)。
这种设计模式是一种控制反转的实现方式。因为高层代码不再确定(控制)算法的处理流程。
用法
编辑模板方法模式多用在:
- 某些类别的算法中,实做了相同的方法,造成代码的重复。
- 控制子类必须遵守的一些事项。
- ...
用例(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
}
}
C++ 例子
编辑#include<iostream>
// abstract
class BaseClass {
protected:
virtual void someMethod() = 0;
public:
void ThisIsTemplateMethod() { someMethod(); }
};
class ExtendedClass_one : public BaseClass {
protected:
void someMethod() override {
puts("[ExtendedClass_one] Re-Define method here.");
}
};
class ExtendedClass_two : public BaseClass {
protected:
void someMethod() override {
puts("[ExtendedClass_two] Re-Define method here.");
}
};
int main() {
BaseClass* one = new ExtendedClass_one;
one->ThisIsTemplateMethod();
BaseClass* two = new ExtendedClass_two;
two->ThisIsTemplateMethod();
return 0;
}