您的位置:首页 > 其它

<Head First 设计模式>:装饰者模式--Beverage

2015-04-19 14:29 316 查看


#ifndef __BEVERAGE_H__
#define __BEVERAGE_H__
#include <string>
using namespace std;
class Beverage
{
public:
Beverage()
{
}
virtual ~Beverage(){}
virtual string getDescripthion()
{
return "Unknown Beverage";
}
virtual float cost() = 0
{

}
};

class Espresso :public Beverage
{
public:
Espresso()
{

}
virtual ~Espresso(){}
virtual float cost()
{
return 1.99f;
}
virtual string getDescripthion()
{
return "Espresso";
}
};

class HouseBlend :public Beverage
{
public:
HouseBlend(){}
virtual ~HouseBlend(){}
virtual float cost()
{
return 0.89;
}
virtual string getDescripthion()
{
return "HouseBlend";
}
};

#endif
#ifndef __DECORATOR_H__
#define __DECORATOR_H__

#include "Beverage.h"
class Decorator : public Beverage
{
public:
Decorator(){}
virtual ~Decorator(){}
virtual string getDescripthion() = 0
{

}
virtual float cost() = 0
{

}
};

class Mocha : public Decorator
{
private:
Beverage *beverage;
public:
Mocha(Beverage *b)
{
beverage = b;
}
virtual ~Mocha(){}
virtual  string  getDescripthion()
{
return beverage->getDescripthion() + ", Mocha";
}
virtual float cost()
{
return beverage->cost() + 0.20;
}
};

class Soy : public Decorator
{
private:
Beverage *beverage;
public:
Soy(Beverage *b)
{
beverage = b;
}
virtual ~Soy(){}
virtual  string  getDescripthion()
{
return beverage->getDescripthion() + ", Soy";
}
virtual float cost()
{
return beverage->cost() + 0.15;
}
};

class Whip : public Decorator
{
private:
Beverage *beverage;
public:
Whip(Beverage *b)
{
beverage = b;
}
virtual ~Whip(){}
virtual  string  getDescripthion()
{
return beverage->getDescripthion() + ", Whip";
}
virtual float cost()
{
return beverage->cost() + 0.10;
}

};

#endif

#include <iostream>
#include "Decorator.h"

using namespace std;
int main()
{
Beverage *ber = new Espresso();
cout << ber->getDescripthion() << "+"<< ber->cost()<<endl;

Beverage *ber2 = new HouseBlend();
ber2 = new Soy(ber2);
ber2 = new Mocha(ber2);
ber2 = new Whip(ber2);
cout << ber2->getDescripthion() << "+" << ber2->cost()<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: