2015/4/28
装饰模式(Decorator),动态的给一个对象添加一些额外的职责,就增加功能来说,装饰模式比生成子类更为灵活。—大话设计模式
#include <vector> #include <iostream> using namespace std; /*基类*/ class Component{ public: virtual void Operation(){ cout<<"的"; }; }; /*被装饰类*/ class ConcreteComponent:public Component{ public: void Operation(){ Component::Operation(); cout<<"小瞿"<<endl; } }; /*装饰类的基类*/ class Decorator:public Component{ private: /* 此处为了让装饰类连成环并且可以指向装饰类也可以指向被装饰类 所以使用了同一个基类指针形成多态 */ Component *pc; public: Decorator(Component *p){ this->pc=p;} virtual void Operation(){ pc->Operation(); } }; class ConcreteDecoratorA:public Decorator{ public: ConcreteDecoratorA(Component *t):Decorator(t){ } void Operation() { cout<<"打着领带"; Decorator::Operation(); } }; class ConcreteDecoratorB:public Decorator{ public: ConcreteDecoratorB(Component *t):Decorator(t){ } void Operation() { cout<<"身穿西装"; Decorator::Operation(); } }; class ConcreteDecoratorC:public Decorator{ public: ConcreteDecoratorC(Component *t):Decorator(t){ } void Operation() { cout<<"穿着皮鞋"; Decorator::Operation(); } }; int main(void) { Component *p=new ConcreteComponent(); Component *p1=new ConcreteDecoratorC(p); Component *p2=new ConcreteDecoratorB(p1); Component *p3=new ConcreteDecoratorA(p2); p3->Operation(); return 0; }
何时使用装饰模式:当系统有了新的功能需要添加的时候,就是向旧的类添加新的修饰代码。
但是具有缺点:装饰模式顺序很重要