以下用C++實做template method pattern。
1/**//*
2(C) OOMusou 2007 http://oomusou.cnblogs.com
3
4Filename : DP_TemplateMethodPattern1.cpp
5Compiler : Visual C++ 8.0 / BCB 6.0 / gcc 3.4.2 / ISO C++
6Description : Demo how to use Template Method Pattern
7Release : 03/31/2007 1.0
8*/
9
10#include <iOStream>
11
12using namespace std;
13
14class DrinkMachine {
15public:
16 void makeDrink();
17
18protected:
19 void boilWater() { cout << "boil some water" << endl; }
20 virtual void doPutIngredIEnt() const = 0;
21 virtual void doPourInCup() const = 0;
22 virtual void doAddFlavoring() const = 0;
23};
24
25void DrinkMachine::makeDrink() {
26 this->boilWater();
27 this->doPutIngredIEnt();
28 this->doPourInCup();
29 this->doAddFlavoring();
30}
31
32class TeaMachine : public DrinkMachine {
33protected:
34 void doPutIngredIEnt() const { cout << "steep tea in boiling water" << endl; }
35 void doPourInCup() const { cout << "pour tea in cup" << endl; }
36 void doAddFlavoring() const {cout << "add lemon" << endl; }
37};
38
39class CoffeeMachine : public DrinkMachine {
40protected:
41 void doPutIngredIEnt() const { cout << "brew coffee in boiling water" << endl; }
42 void doPourInCup() const { cout << "pour coffee in cup" << endl; }
43 void doAddFlavoring() const {cout << "add sugar and milk." << endl; }
44};
45
46int main() {
47 cout << "Making Tea" << endl;
48
49 DrinkMachine *theDrinkMachine = &TeaMachine();
50 theDrinkMachine->makeDrink();
51
52 cout << endl;
53
54 cout << "Making Coffee" << endl;
55 theDrinkMachine = &CoffeeMachine();
56 theDrinkMachine->makeDrink();
57}
執行結果
Making Tea
boil some water
steep tea in boiling water
pour tea in cup
add lemon
Making Coffee
boil some water
brew coffee in boiling water
pour coffee in cup
add sugar and milk.