模板方法(Template Method)模式的定义如下:定义一个操作中的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。它是一种类行为型模式。
#include <QCoreApplication>
#include <iostream>
using namespace std;
class DrinkTemplate{
public:
virtual void BoildWater()=0;//煮水
virtual void Brew()=0; //冲泡
virtual void PourInCup()=0; //倒入杯中
virtual void AddSomething()=0;//加辅料
void Make(){
BoildWater();
Brew();
PourInCup();
AddSomething();
}
};
class Coffee:public DrinkTemplate{
public:
virtual void BoildWater(){
cout<<"zhu shui"<<endl;
}
virtual void Brew(){
cout<<"chong Coffee"<<endl;
}
virtual void PourInCup(){
cout<<"dao ru bei zhong"<<endl;
}
virtual void AddSomething(){
cout<<"add tang"<<endl;
}
};
class Tea:public DrinkTemplate{
public:
virtual void BoildWater(){
cout<<"zhu shui"<<endl;
}
virtual void Brew(){
cout<<"chong tie guang yin"<<endl;
}
virtual void PourInCup(){
cout<<"dao ru bei zhong"<<endl;
}
virtual void AddSomething(){
cout<<"add gou qi"<<endl;
}
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
DrinkTemplate* drink = new Tea;
drink->Make();
delete drink;
cout<<endl;
drink = new Coffee;
drink->Make();
delete drink;
return a.exec();
}