:装饰者模式--Beverage-LMLPHP

#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;
}
05-07 15:50