装饰器模式允许在运行时动态地给一个对象添加一些额外的职责,而不会影响到其他对象。
在C++中,装饰器模式可以通过定义一个抽象组件类和多个装饰器类来实现。
class Component {
public:
virtual void Operation() = 0;
};
class ConcreteComponent : public Component {
public:
void Operation() override {
std::cout << "ConcreteComponent operation." << std::endl;
}
};
class Decorator : public Component {
public:
Decorator(Component* component) : component_(component) {}
void Operation() override {
component_->Operation();
}
protected:
Component* component_;
};
class ConcreteDecoratorA : public Decorator {
public:
ConcreteDecoratorA(Component* component) : Decorator(component) {}
void Operation() override {
Decorator::Operation();
std::cout << "Added ConcreteDecoratorA operation." << std::endl;
}
};
class ConcreteDecoratorB : public Decorator {
public:
ConcreteDecoratorB(Component* component) : Decorator(component) {}
void Operation() override {
Decorator::Operation();
std::cout << "Added ConcreteDecoratorB operation." << std::endl;
}
};