模板模式

板方法模式(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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值