模板方法模式 在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤。
-
#include <iostream>
-
#include <string>
-
-
using namespace std;
-
-
struct CaffeineBeverage {
-
public:
-
prepareRecipe() {
-
boilWater();
-
brew();
-
pourInCup();
-
addCondiments();
-
hook();
-
}
-
virtual brew() = 0;
-
virtual addCondiments() = 0;
-
boilWater() {
-
cout << "boilWater" << endl;
-
}
-
pourInCup() {
-
cout << "pourInCup" << endl;
-
}
-
virtual hook() {}
-
};
-
-
struct Tea : public CaffeineBeverage {
-
public:
-
virtual brew() {
-
cout << "Tea: brew" << endl;
-
}
-
virtual addCondiments() {
-
cout << "Tea: addCondiments" << endl;
-
}
-
};
-
-
struct Coff : public CaffeineBeverage {
-
virtual brew() {
-
cout << "Coff: brew" << endl;
-
}
-
virtual addCondiments() {
-
cout << "Coff: addCondiments" << endl;
-
}
-
virtual hook() {
-
cout << "Coff: hook service" << endl;
-
}
-
};
-
-
-
int main(int argc, char **argv)
-
{
-
Tea *myTea = new Tea();
-
myTea->prepareRecipe();
-
delete myTea;
-
-
Coff *myCoff = new Coff();
-
myCoff->prepareRecipe();
-
delete myCoff;
-
-
return 0;
-
}
阅读(642) | 评论(0) | 转发(0) |