装饰模式是一种结构型设计模式,可以在不改变对象类的情况下,动态地给对象添加新的功能。该模式的核心思想是通过封装原始对象,以便在运行时动态地添加新的行为或状态。

以下是用 C++ 实现装饰模式的示例代码:

// Component接口类,定义了被装饰对象的基本操作 class Component { public: virtual void operation() = 0; };

// ConcreteComponent类,实现Component接口 class ConcreteComponent : public Component { public: void operation() { cout << 'ConcreteComponent operation.' << endl; } };

// Decorator类,继承Component接口,同时包含一个指向Component对象的指针 class Decorator : public Component { public: Decorator(Component* c) : component(c) {} void operation() { component->operation(); } protected: Component* component; };

// ConcreteDecoratorA类,实现Decorator接口,添加新的操作 class ConcreteDecoratorA : public Decorator { public: ConcreteDecoratorA(Component* c) : Decorator(c) {} void operation() { Decorator::operation(); cout << 'ConcreteDecoratorA operation.' << endl; } };

// ConcreteDecoratorB类,实现Decorator接口,添加新的操作 class ConcreteDecoratorB : public Decorator { public: ConcreteDecoratorB(Component* c) : Decorator(c) {} void operation() { Decorator::operation(); cout << 'ConcreteDecoratorB operation.' << endl; } };

// 客户端代码 int main() { // 创建ConcreteComponent对象 Component* c = new ConcreteComponent();

// 用ConcreteDecoratorA包装ConcreteComponent对象
Component* d1 = new ConcreteDecoratorA(c);

// 用ConcreteDecoratorB包装ConcreteDecoratorA对象
Component* d2 = new ConcreteDecoratorB(d1);

// 执行操作
d2->operation();

// 释放内存
delete d2;
delete d1;
delete c;

return 0;

}

输出结果:

ConcreteComponent operation. ConcreteDecoratorA operation. ConcreteDecoratorB operation.


原文地址: https://www.cveoy.top/t/topic/oWeQ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录