美文网首页
装饰模式C++

装饰模式C++

作者: 涵仔睡觉 | 来源:发表于2018-05-15 19:06 被阅读0次

装饰模式,动态地给一个对象添加一些额外的职责,就增加功能而言,装饰模式比生成子类更为灵活。

装饰模式的结构

image

Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义了一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对于Component来说,是无需知道Decorator的存在的。至于ConcreteDecorator就是具体的装饰对象,起到给Component添加职责的功能。

装饰模式的基本代码实现

#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;
}

也就是说,装饰模式是利用SetComponent来对对象进行包装,这样每个装饰对象的实现就和如何使用这个对象分离开了,每个装饰对象只关心自己的功能,不需要关心如何被添加到对象链当中。总的来说,装饰模式是为已有功能动态地增加更多功能的一种方式。

使用场景

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

优点:

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

相关文章

网友评论

      本文标题:装饰模式C++

      本文链接:https://www.haomeiwen.com/subject/wfmydftx.html