程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> 我的Design Pattern之旅[2]:Template Method Pattern(OO)(2)

我的Design Pattern之旅[2]:Template Method Pattern(OO)(2)

編輯:關於C語言

以下用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.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved