**定义:**装饰器模式(Decorator Pattern)是一种结构型设计模式,它允许你向一个现有的对象添加新的功能,同时又不改变其结构。这种类型的设计模式属于对象结构型模式,它是通过创建一个包装对象,也就是装饰器,来包裹真实的对象。
代码:
cpp
// 抽象构件角色
class Component {
public:
virtual ~Component() = default;
virtual void Operation() const = 0;
};
// 具体构件角色
class ConcreteComponent : public Component {
public:
void Operation() const override {
std::cout << "ConcreteComponent" << std::endl;
}
};
// 抽象装饰器角色
class Decorator : public Component {
protected:
std::shared_ptr<Component> component;
public:
Decorator(std::shared_ptr<Component> comp) : component(comp) {}
void Operation() const override {
component->Operation();
}
};
// 具体装饰器角色A
class ConcreteDecoratorA : public Decorator {
public:
ConcreteDecoratorA(std::shared_ptr<Component> comp) : Decorator(comp) {}
void Operation() const override {
Decorator::Operation(); // 调用被装饰对象的Operation()
AddedBehavior(); // 调用附加行为
}
void AddedBehavior() const {
std::cout << "ConcreteDecoratorA - Added Behavior" << std::endl;
}
};
// 具体装饰器角色B
class ConcreteDecoratorB : public Decorator {
public:
ConcreteDecoratorB(std::shared_ptr<Component> comp) : Decorator(comp) {}
void Operation() const override {
AddedBehavior(); // 调用附加行为
Decorator::Operation(); // 调用被装饰对象的Operation()
}
void AddedBehavior() const {
std::cout << "ConcreteDecoratorB - Added Behavior" << std::endl;
}
};
int main() {
// 创建具体构件对象
auto concreteComponent = std::make_shared<ConcreteComponent>();
// 创建装饰器对象并装饰具体构件对象
auto decoratorA = std::make_shared<ConcreteDecoratorA>(concreteComponent);
auto decoratorB = std::make_shared<ConcreteDecoratorB>(decoratorA);
// 执行被装饰后的对象的方法
decoratorB->Operation();
return 0;
}