C++设计模式之装饰模式 C++设计模式之装饰模式(Decorator)
http://www.cnblogs.com/chencar 人气:0想了解C++设计模式之装饰模式(Decorator)的相关内容吗,http://www.cnblogs.com/chencarl/p/8649394.html在本文为您仔细讲解C++设计模式之装饰模式的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C++,设计模式,装饰模式,下面大家一起来学习吧。
装饰模式是一种经典的类功能扩展模式,其精髓在装饰类使用继承加聚合的方式获得接口和要实现对象,然后通过自己实现扩展接口
作用
装饰模式通过装饰类动态地将责任附加到对象上,若要扩展功能,无需通过继承增加子类就能扩展对象的新功能,提供了比继承更有弹性的替代方案,避免了子类数量膨胀带来的系统臃肿。
类视图
代码实现
class Component { public: Component(){} virtual ~Component(){} virtual void operation() = 0; }; class ConcreteComponentA : public Component { public: ConcreteComponentA(){} ~ConcreteComponentA(){} void operation() { fprintf(stderr, "ConcreteComponentA's operation!\n"); } }; class ConcreteComponentB : public Component { public: ConcreteComponentB(){} ~ConcreteComponentB(){} void operation() { fprintf(stderr, "ConcreteComponentB's operation!\n"); } }; class Decorator : public Component { public: Decorator() :mComponent(NULL){} virtual ~Decorator(){} virtual void operation() { if (mComponent) mComponent->operation(); } virtual void setComponent(Component* pComponent) { mComponent = pComponent; } protected: Component* mComponent; }; class ConcreteDecoratorE : public Decorator { public: ConcreteDecoratorE (); virtual ~ConcreteDecoratorE (); virtual void addBehavior() { mComponent->operation(); fprintf(stderr, "ConcreteDecoratorE's addBehavior!\n"); } }; class ConcreteDecoratorF : public Decorator { public: ConcreteDecoratorF (); virtual ~ConcreteDecoratorF (); virtual void addBehavior() { operation(); fprintf(stderr, "ConcreteDecoratorF's addBehavior!\n"); } }; int main() { ConcreteComponentB *pComponent = new ConcreteComponentB(); ConcreteDecoratorF decorator; decorator.setComponent(pComponent); decorator.addBehavior(); }
加载全部内容