首页 > 编程 > C++ > 正文

C++设计模式之装饰模式(Decorator)

2020-01-26 13:44:11
字体:
来源:转载
供稿:网友

装饰模式是一种经典的类功能扩展模式,其精髓在装饰类使用继承加聚合的方式获得接口和要实现对象,然后通过自己实现扩展接口

作用
装饰模式通过装饰类动态地将责任附加到对象上,若要扩展功能,无需通过继承增加子类就能扩展对象的新功能,提供了比继承更有弹性的替代方案,避免了子类数量膨胀带来的系统臃肿。

类视图

代码实现

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();}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表