设计模式之模板方法模式

模板方法模式

定义

在一个方法中定义一个算法的骨架,将一些步骤延迟到子类中,模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。

类图

CahYdg.jpg

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class CaffeineBeverage {
public:
void prepareRecipe() {
cout << "**********************" << endl;
cout << "prepare...." << endl;
boilWater();
pourInCup();
brew();
addCondiments();
}

void boilWater() {
cout << "boil water" << endl;
}

void pourInCup() {
cout << "pour in cup" << endl;
}

virtual void brew() {};
virtual void addCondiments() {};
};

class Coffee :public CaffeineBeverage {
public:
void brew() {
cout << "dripping coffee" << endl;
}

void addCondiments() {
cout << "adding sugar and milk" << endl;
}
};

class Tea :public CaffeineBeverage {
public:
void brew() {
cout << "steeping the coffee" << endl;
}

void addCondiments() {
cout << "adding lemon" << endl;
}
};

理解

在接口中定义一个算法的框架,分为多个步骤,子类可以改变其中的某些步骤。STL中的很多算法都可以传入自定义的比较函数,此即为模板方法模式。

分享到