#include <iostream>
#include <string>
using namespace std;
class Beverage
{
public:
Beverage():description("Unknown Beverage")
{
}
virtual std::string getDescription()//:description = "Unknown Beverage"
{
return description;
}
virtual double cost() = 0;
//{
// return 0;
//};
string description ;
protected:
private:
};
class CondimenteDecorator :public Beverage
{
public:
virtual string getDescription() = 0;
//{
// return description;
//}
protected:
private:
};
class Espresso :public Beverage
{
public:
Espresso()
{
description = "Espresso";
}
double cost()
{
return 1.99;
}
};
class HouseBlend :public Beverage
{
public:
HouseBlend()
{
description = "HouseBlend";
}
double cost()
{
return 0.99;
}
};
class DarkRoast :public Beverage
{
public:
DarkRoast()
{
description = "DarkRoast";
}
double cost()
{
return 0.88;
}
};
class Mocha :public CondimenteDecorator
{
public:
Mocha(Beverage *bevergage)
{
this->bevergage = bevergage;
}
string getDescription()
{
return bevergage->getDescription() + string(" Mocha");
}
double cost()
{
return 0.20 + bevergage->cost();
}
protected:
private:
Beverage *bevergage;
};
class Whip :public CondimenteDecorator
{
public:
Whip(Beverage *bevergage)
{
this->bevergage = bevergage;
}
string getDescription()
{
return bevergage->getDescription() + " Whip";
}
double cost()
{
return 0.40 + bevergage->cost();
}
protected:
private:
Beverage *bevergage;
};
class Soy :public CondimenteDecorator
{
public:
Soy(Beverage *bevergage)
{
this->bevergage = bevergage;
}
string getDescription()
{
return bevergage->getDescription() + " Soy";
}
double cost()
{
return 0.40 + bevergage->cost();
}
protected:
private:
Beverage *bevergage;
};
#include "Beverage.h"
int main()
{
Beverage *pBeverage = new Espresso;
std::cout<<pBeverage->getDescription().c_str()<<" $"<<pBeverage->cost()<<std::endl;
Beverage *pBeverage2 = new DarkRoast;
pBeverage2 = new Mocha(pBeverage2);
pBeverage2 = new Mocha(pBeverage2);
pBeverage2 = new Whip(pBeverage2);
std::cout<<pBeverage2->getDescription().c_str()<<" $"<<pBeverage2->cost()/**/<<std::endl;
Beverage *pBeverage3 = new HouseBlend;
pBeverage3 = new Soy(pBeverage3);
pBeverage3 = new Mocha(pBeverage3);
pBeverage3 = new Whip(pBeverage3);
std::cout<<pBeverage3->getDescription().c_str()<<" $"<<pBeverage3->cost()<<std::endl;
return 0;
}
这才是真正的装饰模式!
回复 更多评论