装饰者模式

来源:互联网 发布:mysql strcmp 编辑:程序博客网 时间:2024/04/30 12:01

利用继承设计子类行为,是在编译时静态决定的,而且所有的子类都会继承到相同的行为,而如果能利用组合的做法扩展对象的行为,就可以在运行时动态地进行扩展。通过动态地组合对象,可以写新的代码添加新功能,而无须修改现有的代码,这样可以使得引入bug或产生意外副作用的机会将大幅减少。

设计原则:类应该对扩展开放,对修改关闭

1.装饰者和被装饰对象有相同的超类型

2.可以用一个或多个装饰者包装一个对象

3.既然装饰者和被装饰对象有相同的超类型,所以在任何需要原始对象的场合,都可以用装饰过的对象代替它

4.装饰者可以在所委托被装饰者的行为之前或之后加上自己的行为,以达到特定的目的

5.对象可以在任何时候被装饰,所以可以在运行时动态地、不限量地用自己喜欢的装饰者来装饰对象


#ifndef _DECORATOR_H#define _DECORATOR_H#include<iostream>#include<string>using namespace std;class Beverage{protected:string description;public:Beverage(string description) :description(description){}Beverage(){}virtual string getDescription(){return description;}virtual double cost() = 0;};class CondimentDecorator :public Beverage{};class Espresso :public Beverage{public:Espresso() :Beverage("Espresso"){}double cost(){return 1.99;}};class HouseBlend :public Beverage{public:HouseBlend() :Beverage("House Blend Coffee"){}double cost(){return 0.89;}};class DarkRoast :public Beverage{public:DarkRoast() :Beverage("Drak Roast Coffee"){}double cost(){return 1.20;}};class Mocha :public CondimentDecorator{private:Beverage *beverage;public:Mocha(Beverage *beverage) : beverage(beverage){}string getDescription(){return beverage->getDescription() + ", Mocha";}double cost(){return beverage->cost() + 0.20;}};class Whip :public CondimentDecorator{private:Beverage *beverage;public:Whip(Beverage *beverage) :beverage(beverage){}string getDescription(){return beverage->getDescription() + ", Whip";}double cost(){return beverage->cost() + 0.35;}};#endif
#include"Decorator.h"int main(){Beverage* beverage = new Espresso();cout << beverage->getDescription() << " $" << beverage->cost() << endl;Beverage* beverage2 = new HouseBlend();beverage2= new Mocha(beverage2);beverage2 = new Mocha(beverage2);beverage2 = new Whip(beverage2);cout << beverage2->getDescription() << " $" << beverage2->cost() << endl;}




0 0