标签:
模板方法模式: 在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中.模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤.
好莱坞原则: 低层组件绝对不可以调用高层组件,高层组件控制何时以及如何让低层组件参与.好莱坞原则教我们一个技巧,创建一个有弹性的设计.
#ifndef CAFFEINEBEVERAGE_H #define CAFFEINEBEVERAGE_H #include <iostream> using namespace std; class CaffeineBeverage { public: void prepareRecipe() { boilWater(); brew(); pourInCup(); if (customerWantsCondiments()) { addCondiments(); } } virtual void brew() = 0; virtual void addCondiments() = 0; void boilWater() { cout<<"Boiling water"<<endl; } void pourInCup() { cout<<"Pouring into cup"<<endl; } //可以对Hook使用策略模式优化。 virtual bool customerWantsCondiments() { return true; } }; #endif
#ifndef TEA_H #define TEA_H #include "CaffeineBeverage.h" #include <iostream> using namespace std; class Tea : public CaffeineBeverage { public: void brew() { cout<<"Steeping the tea"<<endl; } void addCondiments() { cout<<"Adding Lemon"<<endl; } }; #endif
#ifndef COFFEE_H #define COFFEE_H #include "CaffeineBeverage.h" #include <iostream> #include <string> using namespace std; class Coffee : public CaffeineBeverage { public: void brew() { cout<<"Dripping Coffee through filter"<<endl; } void addCondiments() { cout<<"Adding Sugar and Milk"<<endl; } bool customerWantsCondiments() { string answer = string(""); cout<<"Would you like milk and sugar with your coffee (y/n)?"<<endl; cin>>answer; if (answer == string("y")) { return true; } else { return false; } } }; #endif
#include "CaffeineBeverage.h" #include "Coffee.h" #include "Tea.h" int main() { Tea* tea = new Tea; tea->prepareRecipe(); Coffee* coffee = new Coffee; coffee->prepareRecipe(); return 0; }
标签:
原文地址:http://www.cnblogs.com/lisiyuannnn/p/4897501.html