设计模式-装饰器模式

发布于:2025-07-01 ⋅ 阅读:(20) ⋅ 点赞:(0)

设计模式-装饰器模式

前言

由于作者做的C++开发比较多所以本文实例都以C++语言方式给出。

装饰器模式

// 组件接口
class Component {
public:
    virtual ~Component() = default;
    virtual std::string operation() const = 0;
};

// 具体组件
class ConcreteComponent : public Component {
public:
    std::string operation() const override {
        return "ConcreteComponent";
    }
};

// 装饰器基类
class Decorator : public Component {
protected:
    Component* component_;

public:
    Decorator(Component* component) : component_(component) {}
    std::string operation() const override {
        return component_->operation();
    }
};

// 具体装饰器A
class ConcreteDecoratorA : public Decorator {
public:
    ConcreteDecoratorA(Component* component) : Decorator(component) {}
    
    std::string operation() const override {
        return "ConcreteDecoratorA(" + Decorator::operation() + ")";
    }
};

// 具体装饰器B
class ConcreteDecoratorB : public Decorator {
public:
    ConcreteDecoratorB(Component* component) : Decorator(component) {}
    
    std::string operation() const override {
        return "ConcreteDecoratorB(" + Decorator::operation() + ")";
    }
};

装饰器模式的核心概念:通过嵌套装饰器来动态添加功能。代码包含组件接口、具体组件、装饰器基类和两个具体装饰器实现。
上面例子Component类作为接口类,ConcreteComponent可以看作是一个实现Component的一个具体组件,现在如果想在这个组件中增加新的东西但是不想修改原来的ConcreteComponent类,就可以创建ConcreteDecoratorA装饰器类来持有Component(实际是ConcreteComponent对象),ConcreteDecoratorA对象继承于Decorator而Decorator继承于Component,因此ConcreteDecoratorA,和ConcreteComponent对外有相同的接口virtual std::string operation() const = 0;(也可以是其他接口例子中只写了一个operation()接口),接口相同对于外界调用者来说可以说是无感的。ConcreteDecoratorA的operation()函数可以调用持有的Component的operation()来保持原有的功能,可以通过在调用前后增加一些内容来实现装饰器新增的一些功能。


网站公告

今日签到

点亮在社区的每一天
去签到