标签:
装饰者模式:动态地将责任附加到对象上。若要扩展功能,装饰者提供了比继承更有弹性的替代方案。
#ifndef BEVERAGE_H #define BEVERAGE_H #include <string> using namespace std; class Beverage { public: Beverage(string s):description(s) { } Beverage(){} virtual string getDescription() { return description; } virtual double cost() = 0; protected: string description; }; #endif
#ifndef DARKROAST_H #define DARKROAST_H #include "Beverage.h" class DarkRoast : public Beverage { public: DarkRoast ():Beverage("DarkRoast") {} double cost() { return 30; } }; #endif
#ifndef DECAF_H #define DECAF_H #include "Beverage.h" class Decaf : public Beverage { public: Decaf() : Beverage("Decaf") {} double cost() { return 50; } }; #endif
#ifndef ESPRESSO_H #define ESPRESSO_H #include "Beverage.h" class Espresso : public Beverage { public: Espresso() : Beverage("Espresso") {} double cost() { return 40; } }; #endif
#ifndef HOUSEBLEND_H #define HOUSEBLEND_H #include "Beverage.h" class HouseBlend : public Beverage { public: HouseBlend():Beverage("HouseBlend") {} double cost() { return 20; } }; #endif
#ifndef CONDIMENTDECORATOR_H #define CONDIMENTDECORATOR_H #include "Beverage.h" class CondimentDecorator : public Beverage { public: virtual string getDescription() = 0; }; #endif
#ifndef MILK_H #define MILK_H #include "CondimentDecorator.h" #include "Beverage.h" class Milk : public CondimentDecorator { private: Beverage* beverage; public: Milk( Beverage* b ) { beverage = b; } Milk(){} virtual ~Milk() { if (NULL!=beverage) { delete beverage; beverage = NULL; } } double cost () { return beverage->cost() + 0.1; } string getDescription() { return beverage->getDescription() + "," + "Milk"; } }; #endif
#ifndef MOCHA_H #define MOCHA_H #include "CondimentDecorator.h" #include "Beverage.h" class Mocha : public CondimentDecorator { private: Beverage* beverage; public: Mocha( Beverage* b ) { beverage = b; } Mocha(){} virtual ~Mocha() { if (NULL != beverage) { delete beverage; beverage = NULL; } } double cost () { return beverage->cost() + 0.2; } string getDescription() { return beverage->getDescription() + "," + "Mocha"; } }; #endif
标签:
原文地址:http://www.cnblogs.com/lisiyuannnn/p/4760755.html