Model(模式,XML数据或者一组API)本身不知道将被怎么使用。实际的算法被委托给 View (视图),也就是 模板。模板方法是MVC的一个子集,不包括C。
在面向对象语言里,首先一个类使用虚函数实现一个基本的算法设计,然后的继承的子类里实现实际的方法。通用算法只实现一次,实际的步骤的具体的子类里修改。
使用:
- 让子类实现可变的行为。
- 避免代码重复。找出算法中的通用代码,把变化的部分在子类中实现。
- 控制哪些可以子类化。即哪些可以重载。
例子:
/**
* 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 {
protected 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() {
// Initialize money
}
void makePlay(int player) {
// Process one turn of player
}
boolean endOfGame() {
// Return true of game is over according to Monopoly rules
}
void printWinner() {
// Display who won
}
/* Specific declarations for the Monopoly game. */
// ...
}
class Chess extends Game {
/* Implementation of necessary concrete methods */
void initializeGame() {
// Put the pieces on the board
}
void makePlay(int player) {
// Process a turn for the player
}
boolean endOfGame() {
// Return true if in Checkmate or Stalemate has been reached
}
void printWinner() {
// Display the winning player
}
/* Specific declarations for the chess game. */
// ...
}