[架构设计]设计模式C++实现--模板方法模式
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
模式定义:
模板方法模式在一个方法中定义了一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
模板就是一个方法。更具体的说,这个方法将算法定义成一组步骤,其中的任何步骤都可以是抽象的,由子类实现。这可以确保算法的结果保持不变,同时由子类提供部分实现。
模式结构:
举例:
泡咖啡和泡茶步骤与基本相同,定义咖啡和茶的类如下:
[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" < 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" < 57. } 58. 59.void addLemon() 60. { 61. cout << "Adding Lemon" << endl; 62. } 63.}; 可见有两份冲泡算法中都采用了把水煮沸和把饮料倒入杯子的 算法,所以可以把他们放到Coffee和Tea的基类(新定义一个咖啡因类CaffeineBeverage.)中。还有两个算法并没有被放入基类,但可以将他们定义新的方法名称brew()和addCondiments()方法,并在子类中实现。UML设计: 编程实现及执行结果:[cpp]view plaincopy 1.#include 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" < 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;