板方法模式(Template Method Pattern)是如此的easy,以致让你感觉你已经能够掌握其精髓了。其定义如下:
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure。定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
#include <iostream>
#include <string>#include <cctype>
using namespace std;
class CafeineBeverageWithHook
{
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;
}
virtual bool customerWantsCondiments()
{
return true;
}
};
class TeaWithHook:public CafeineBeverageWithHook
{
public:
void brew()
{
cout<<"Steeping the tea"<<endl;
}
void addCondiments()
{
cout<<"Adding Lemon"<<endl<<endl;
}
bool customerWantsCondiments()
{
string answer=getUserInput();
if(answer.substr(0,1)=="y"||answer.substr(0,1)=="Y")
{
return true;
}
else
return false;
}
private:
string getUserInput()
{
string answer="";
cout<<("Would you like Lemon with your coffee(y/n)?");
cin>>answer;
return answer;
}
};
class CoffeWithHook :public CafeineBeverageWithHook
{
public:
void brew()
{
cout<<"Dripping Coffee through filter"<<endl;
}
void addCondiments()
{
cout<<"Adding Sugar and Milk"<<endl;
}
bool customerWantsCondiments()
{
string answer=getUserInput();
if(answer.substr(0,1)=="y"||answer.substr(0,1)=="Y")
{
return true;
}
else
return false;
}
private:
string getUserInput()
{
string answer="";
cout<<("Would you like milk and sugar with your coffee(y/n)?");
cin>>answer;
return answer;
}
};
int main()
{
TeaWithHook *teaHook=new TeaWithHook();
CoffeWithHook *coffewithhook=new CoffeWithHook();
cout<<"Making tea"<<endl;
teaHook->prepareRecipe();
cout<<"Making Coffe"<<endl;
coffewithhook->prepareRecipe();
return 0;
}