开发设计模式设计模式之Decorator模式
Hoshea Zhang动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator 模式相比生成子类更为灵活
它允许你在不改变对象自身的基础上,动态地给对象添加新的功能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| class Component { public: virtual void operation() = 0; };
class ConcreteComponent : public Component { public: void operation() override { } };
class Decorator : public Component { public: Decorator(Component* component) : component_(component) {}
void operation() override { component_->operation(); }
protected: Component* component_; };
class ConcreteDecoratorA : public Decorator { public: ConcreteDecoratorA(Component* component) : Decorator(component) {}
void operation() override { Decorator::operation(); addBehaviorA(); }
void addBehaviorA() { } };
class ConcreteDecoratorB : public Decorator { public: ConcreteDecoratorB(Component* component) : Decorator(component) {}
void operation() override { Decorator::operation(); addBehaviorB(); }
void addBehaviorB() { } };
int main() { Component* component = new ConcreteComponent(); Decorator* decoratorA = new ConcreteDecoratorA(component); Decorator* decoratorB = new ConcreteDecoratorB(decoratorA);
decoratorB->operation();
return 0; }
|
通过使用装饰器模式,我们可以在运行时动态地给对象添加新的功能,而不需要改变对象自身的代码。这使得我们可以更加灵活地扩展代码,并且可以避免创建大量的子类。