C++常用23种设计模式总结(三)------装饰模式
往期回顾
C++常用23种设计模式总结(一)------单例模式
C++常用23种设计模式总结(二)------观察者模式
什么是装饰模式
装饰模式是一种结构型设计模式,它允许你在运行时为对象动态添加新的行为。该模式通过将对象放入包装器中来实现这一点,这个包装器会实现与被包装对象相同的接口,并且会将所有方法的调用委派给被包装对象。同时,包装器还可以定义一些额外的行为,例如添加新的方法或修改现有方法的行为。
装饰模式的主要优点是它允许你在不修改现有代码的情况下扩展对象的功能。这使得代码更加灵活和可维护,因为你可以通过添加新的装饰器来实现新的功能,而不必修改现有的代码。此外,装饰模式还遵循开闭原则,因为它允许你在不修改现有代码的情况下添加新的功能。
然而,装饰模式也有一些缺点。首先,由于每个装饰器都需要实现与被包装对象相同的接口,因此可能会导致类的数量增加。此外,由于装饰器可以嵌套,因此可能会导致代码变得复杂和难以理解。最后,装饰模式可能会导致性能下降,因为每个方法调用都需要经过多个装饰器的处理。
参考代码
#include <iostream>// 抽象组件
class Component {
public:virtual void operation() = 0;
};// 具体组件
class ConcreteComponent : public Component {
public:void operation() override {std::cout << "具体组件的操作" << std::endl;}
};// 抽象装饰器
class Decorator : public Component {
public:Decorator(Component* comp) : component(comp) {}void operation() override {if (component != nullptr) {component->operation();}}
protected:Component* component;
};/*续写*/// 具体装饰器A
class ConcreteDecoratorA : public Decorator {
public:ConcreteDecoratorA(Component* comp) : Decorator(comp) {}void operation() override {Decorator::operation();std::cout << "具体装饰器A的操作" << std::endl;}
};// 具体装饰器B
class ConcreteDecoratorB : public Decorator {
public:ConcreteDecoratorB(Component* comp) : Decorator(comp) {}void operation() override {Decorator::operation();std::cout << "具体装饰器B的操作" << std::endl;}
};int main() {Component* component = new ConcreteComponent();Component* decoratorA = new ConcreteDecoratorA(component);Component* decoratorB = new ConcreteDecoratorB(decoratorA);decoratorB->operation();delete decoratorB;delete decoratorA;delete component;return 0;
}
运行结果
具体组件的操作
具体装饰器A的操作
具体装饰器B的操作