当前位置:文档之家› [架构设计]设计模式C++实现--模板方法模式

[架构设计]设计模式C++实现--模板方法模式

模式定义:
模板方法模式在一个方法中定义了一个算法的骨架,而将一些步骤延迟到子类中。

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

模板就是一个方法。

更具体的说,这个方法将算法定义成一组步骤,其中的任何步骤都可以是抽象的,由子类实现。

这可以确保算法的结果保持不变,同时由子类提供部分实现。

模式结构:
举例:
泡咖啡和泡茶步骤与基本相同,定义咖啡和茶的类如下:
[cpp]view plaincopy
1.class Coffee
2.{
3.public:
4.void prepareRecipe()
5. {
6. boilWater();
7. brewCoffeeGrinds();
8. pourInCup();
9. addSugarAndMilk();
10. }
11.
12.void boilWater()
13. {
14. cout << "Boiling water" << endl;
15. }
16.
17.void brewCoffeeGrinds()
18. {
19. cout << "Dripping Coffee through filter" << endl;
20. }
21.
22.void pourCup()
23. {
24. cout << "Pouring into cup" <<endl;
25. }
26.
27.void addSugarAndMilk()
28. {
29. cout << "Adding Sugar and Milk" << endl;
30. }
31.};
32.
33.class Tea
34.{
35.public:
36.void prepareRecipe()
37. {
38. boilWater();
39. brewReaBag();
40. pourInCup();
41. addLemon();
42. }
43.
44.void boilWater()
45. {
46. cout << "Boiling water" << endl;
47. }
48.
49.void brewReaBag()
50. {
51. cout << "Steeping the tea" << endl;
52. }
53.
54.void pourCup()
55. {
56. cout << "Pouring into cup" <<endl;
57. }
58.
59.void addLemon()
60. {
61. cout << "Adding Lemon" << endl;
62. }
63.};
可见有两份冲泡算法中都采用了把水煮沸和把饮料倒入杯子的
算法,所以可以把他们放到Coffee和Tea的基类(新定义一个咖啡因类CaffeineBeverage.)中。

还有两个算法并没有被放入基类,但可以将他们定义新的方法名称brew()和addCondiments()方法,并在子类中实现。

UML设计:
编程实现及执行结果:[cpp]view plaincopy
1.#include <iostream>
2.
ing namespace std;
4.
5.//定义咖啡因基类
6.class CaffeineBeverage
7.{
8.public:
9.void prepareRecipe()
10. {
11. boilWater();
12. brew();
13. pourInCup();
14. addCondiments();
15. }
16.
17.void boilWater()
18. {
19. cout << "Boiling water" << endl;
20. }
21.
22.void pourInCup()
23. {
24. cout << "Pouring into cup" <<endl;
25. }
26.
27.virtual void brew(){}
28.
29.virtual void addCondiments(){}
30.};
31.//定义咖啡类
32.class Coffee : public CaffeineBeverage
33.{
34.public:
35.void brew()
36. {
37. cout << "Dripping Coffee through filter" << endl;
38. }
39.
40.void addCondiments()
41. {
42. cout << "Adding Sugar and Milk" << endl;
43. }
44.};
45.//定义茶类
46.class Tea : public CaffeineBeverage
47.{
48.public:
49.void brew()
50. {
51. cout << "Steeping the tea" << endl;
52. }
53.
54.void addCondiments()
55. {
56. cout << "Adding Lemon" << endl;
57. }
58.};
59.//客户代码
60.int main()
61.{
62. Coffee coffee;
63. cout << "Making coffee..." << endl;
64. coffee.prepareRecipe();
65. cout << endl << endl;
66.
67. Tea tea;
68. cout << "Make tea...";
69. tea.prepareRecipe();
70.return 0;
71.}
执行结果如下:Makingcoffee...
Boilingwater
DrippingCoffee through filter Pouringinto cup AddingSugar and Milk
Maketea...Boiling water Steepingthe tea
Pouringinto cup AddingLemon
请按任意键继续. . .
设计原则的应用:
好莱坞原则:别调用(打电话)我们,我们会调用你。

在好莱坞原则下,我们允许低层组件将自己挂钩到系统上,但是高层组件会决定什么时候和怎么样使用这些低层组件。

如在模板方法中:当我们设计模板方法模式时,我们告诉子类,“不要调用我们,我们会调用你”。

相关主题