C++设计模式——装饰模式Bridge-Pattern

动机(Motivation)

  • 在某些情况下我们可能会“过度地使用继承来扩展对象的功能”,由于继承为类型引入的静态特质,使得这种扩展方式缺乏灵活性; 并且随着子类的增多(扩展功能的增多),各种子类的组合(扩展功能的组合)会导致更多子类的膨胀。
  • 如何使“对象功能的扩展”能够根据需要来动态地实现?同时避免“扩展功能的增多”带来的子类膨胀问题?从而使得任何“功能扩展变化”所导致的影响将为最低?

模式定义

动态(组合)地给一个对象增加一些额外的职责。就增加功能而言,Decorator模式比生成子类(继承)更为灵活(消除重复代码 & 减少子类个数)。 ——《设计模式》GoF

要点总结

  • 通过采用组合而非继承的手法, Decorator模式实现了在运行时动态扩展对象功能的能力,而且可以根据需要扩展多个功能。 避免了使用继承带来的“灵活性差”和“多子类衍生问题”。
  • Decorator类在接口上表现为is-a Component的继承关系,即Decorator类继承了Component类所具有的接口。 但在实现上又表现为has-a Component的组合关系,即Decorator类又使用了另外一个Component类。
  • Decorator模式的目的并非解决“多子类衍生的多继承”问题,Decorator模式应用的要点在于解决“主体类在多个方向上的扩展功能”——是为“装饰”的含义。

结构(Structure)

 

 

  • Component:定义一个对象接口,可以给这些对象动态地添加职责。
  • ConcreteComponent:定义一个对象,可以给这个对象添加一些职责。
  • Decorator:维持一个只想Component对象的指针,并定义一个与Component接口一致的接口。
  • ConcreteDecorator:向组建添加职责。

基本代码

#include <iostream>
#include <string>
using namespace std;

class Component { // 接口
public:
    virtual void Operation() = 0;
    virtual ~Component() {}
};

class ConcreteComponent : public Component { // 具体实现对象,需要被装饰的类
public:
    void Operation() { cout << "ConcreteComponent" << endl; }
};

class Decorator : public Component {
private:
    Component* component;
public:
    void SetComponent(Component* c) { component = c; }  // 设置Component
    virtual void Operation() {
        if (component) component->Operation();
    }
};

class ConcreteDecoratorA : public Decorator {
private:
    string addedState;   // 本类独有功能
public:
    void Operation() {
        Decorator::Operation();
        addedState = "New state";
        cout << "ConcreteDecoratorA: " << addedState << endl;
    }
};

class ConcreteDecoratorB : public Decorator {
private:
    void AddedBehavior() { cout << "ConcreteDecoratorB: AddedBehavior" << endl; }   // 本类特有方法
public:
    void Operation() {
        Decorator::Operation();
        AddedBehavior();
    }
};

int main() {
    Component* c = new ConcreteComponent();
    
    Decorator* d1 = new ConcreteDecoratorA();
    d1->SetComponent(c);
    d1->Operation();  // ConcreteComponent
                      // ConcreteDecoratorA: New state
    Decorator* d2 = new ConcreteDecoratorB();
    d2->SetComponent(c);
    d2->Operation();  // ConcreteComponent
                      // ConcreteDecoratorB: AddedBehavior
    delete d1;
    delete d2;
    delete c;
    return 0;
}

当系统需要增加新功能时,如果向旧的类中添加新的代码,通常这些代码是装饰了原有类的核心职责或主要行为,它们在主类中加入了新的字段、新的方法和新的逻辑,从而增加了主类的复杂度,而这些新加入的代码仅仅只是为了满足一些只在某种特定情况下才会执行的特殊行为的需求。这时装饰模式就是一个非常好的解决方案,它把每个要装饰的功能放在单独的类中,并让这个类包装它所要装饰的对象,因此,当需要执行特殊行为时,客户代码就可以在运行时根据需要有选择、按顺序地使用装饰功能包装对象了。

优点:

  • 把类中的装饰功能从类中搬移去除,这样可以简化原有的类;
  • 有效地把类的核心职责和装饰功能区分开了,而且可以去除相关类中重复的装饰逻辑。

 

posted @ 2020-04-10 09:41  王陸  阅读(306)  评论(0编辑  收藏  举报