您的位置:首页 > 编程语言 > C语言/C++

Head First设计模式C++实现-Decorator模式

2008-12-04 22:02 381 查看
#ifndef DECORATOR_H_

#define DECORATOR_H_

#include <string>

using namespace std;

class Beverage

{

public:

virtual string GetDescription()

{

return "Unknown Beverage";

}

virtual double Cost() = 0;

};

class HouseBlend : public Beverage

{

public:

HouseBlend()

{

}

double Cost()

{

return 0.89;

}

string GetDescription()

{

return "House Blend Coffee";

}

};

class DarkRoast : public Beverage

{

public:

DarkRoast()

{

}

double Cost()

{

return 0.99;

}

string GetDescription()

{

return "Dark Roast Coffee";

}

};

class CondimentDecorator : public Beverage

{

public:

CondimentDecorator(Beverage* bev)

{

beverage = bev;

}

protected:

Beverage* beverage;

};

class Soy : public CondimentDecorator

{

public:

Soy(Beverage* bev):CondimentDecorator(bev)

{

}

string GetDescription()

{

return beverage->GetDescription() + ", Soy";

}

double Cost()

{

return 0.15 + beverage->Cost();

}

};

class SteamedMilk : public CondimentDecorator

{

public:

SteamedMilk(Beverage* bev):CondimentDecorator(bev)

{

}

string GetDescription()

{

return beverage->GetDescription() + ", Steamed Milk";

}

double Cost()

{

return 0.10 + beverage->Cost();

}

};

class Whip : public CondimentDecorator

{

public:

Whip(Beverage* bev):CondimentDecorator(bev)

{

}

string GetDescription()

{

return beverage->GetDescription() + ", Whip";

}

double Cost()

{

return 0.10 + beverage->Cost();

}

};

#endif

/****************测试代码**********/

#include "Decorator.h"

#include <iostream>

using namespace std;

void main()

{

Beverage* beverage = new HouseBlend;

beverage = new SteamedMilk(beverage);

beverage = new Whip(beverage);

cout<<beverage->GetDescription()<<" $ "<<beverage->Cost()<<endl;

}

程序输出:

House Blend Coffee, Steamed Milk, Whip $ 1.09

请按任意键继续. . .
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: