模板方法模式![]() 模板方法(英語:template method),是一種行为型软件设计模式。这种设计模式是一种控制反转的实现方式。因为高层代码不再确定(控制)算法的处理流程。 模板方法是一個定義在父類別的方法,负责处理流程、算法的不变部分。模板方法會调用多個定義在父類別的其他工具方法,而這些方法是算法的可变部分,有可能只是抽象方法並沒有實作,或者是只有空体的钩子方法。模板方法僅決定這些抽象方法的執行順序,這些抽象方法由子類別負責實作,並且子類別不允許覆盖模板方法(即不能重写处理流程)。 用法模板方法模式多用在:
结构![]() 在上面的UML类图中,
用例C++下面是C++的例子: ![]() #include <iostream>
#include <memory>
class View { // AbstractClass
public:
// defines abstract primitive operations that concrete subclasses define to implement steps of an algorithm.
virtual void doDisplay() {}
// implements a template method defining the skeleton of an algorithm.
// The template method calls primitive operations as well as operations defined in AbstractClass or those of other objects.
void display() {
setFocus();
doDisplay();
resetFocus();
}
virtual ~View() = default;
private:
void setFocus() {
std::cout << "View::setFocus\n";
}
void resetFocus() {
std::cout << "View::resetFocus\n";
}
};
class MyView : public View { // ConcreteClass
// implements the primitive operations to carry out subclass-specific steps of the algorithm.
void doDisplay() override {
// render the view's contents
std::cout << "MyView::doDisplay\n";
}
};
int main() {
// The smart pointers prevent memory leaks
std::unique_ptr<View> myview = std::make_unique<MyView>();
myview->display();
}
这个程序的输出为: View::setFocus
MyView::doDisplay
View::resetFocus
Python下面是Python的例子: from abc import ABC, abstractmethod
class View(ABC):
@abstractmethod
def do_display(self): pass
def display(self):
self.__set_focus()
self.do_display()
self.__reset_focus()
def __set_focus(self):
print("View: set focus")
def __reset_focus(self):
print("View: reset focus")
class MyView(View):
def do_display(self):
print("View: do display")
其执行: >>> view = MyView()
>>> view.display()
View: set focus
View: do display
View: reset focus
Java下面是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 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
}
}
引用
|
Index:
pl ar de en es fr it arz nl ja pt ceb sv uk vi war zh ru af ast az bg zh-min-nan bn be ca cs cy da et el eo eu fa gl ko hi hr id he ka la lv lt hu mk ms min no nn ce uz kk ro simple sk sl sr sh fi ta tt th tg azb tr ur zh-yue hy my ace als am an hyw ban bjn map-bms ba be-tarask bcl bpy bar bs br cv nv eml hif fo fy ga gd gu hak ha hsb io ig ilo ia ie os is jv kn ht ku ckb ky mrj lb lij li lmo mai mg ml zh-classical mr xmf mzn cdo mn nap new ne frr oc mhr or as pa pnb ps pms nds crh qu sa sah sco sq scn si sd szl su sw tl shn te bug vec vo wa wuu yi yo diq bat-smg zu lad kbd ang smn ab roa-rup frp arc gn av ay bh bi bo bxr cbk-zam co za dag ary se pdc dv dsb myv ext fur gv gag inh ki glk gan guw xal haw rw kbp pam csb kw km kv koi kg gom ks gcr lo lbe ltg lez nia ln jbo lg mt mi tw mwl mdf mnw nqo fj nah na nds-nl nrm nov om pi pag pap pfl pcd krc kaa ksh rm rue sm sat sc trv stq nso sn cu so srn kab roa-tara tet tpi to chr tum tk tyv udm ug vep fiu-vro vls wo xh zea ty ak bm ch ny ee ff got iu ik kl mad cr pih ami pwn pnt dz rmy rn sg st tn ss ti din chy ts kcg ve