当前位置:
首页 >
C++设计模式-装饰模式
发布时间:2025/3/15
32
豆豆
生活随笔
收集整理的这篇文章主要介绍了
C++设计模式-装饰模式
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
目录
基本概念
代码和实例
基本概念
装饰模式是为已有功能动态地添加更多功能的一种方式。
当系统需要新功能的时候,是向旧系统的类中添加新代码。这些新代码通常装饰了原有类的核心职责或主要行为。
装饰模式的优点:
1. 把类中的装饰功能从类中搬移出去,这样可以简化原有的类;
2. 有效地把类的核心职责和装饰功能区分开了。而且可以去除相关类中重复的装饰逻辑。
代码和实例
结构图如下(使用的大话设计模式的结构图)
程序运行截图如下:
代码如下:
Head.h
#ifndef HEAD_H #define HEAD_H#include <iostream> #include <string> using namespace std;class Component{public:virtual void Operation(){} };class ConcreteComponent: public Component{public:void Operation(); };class Decorator: public Component{public:Decorator();void setComponent(Component *component);void Operation();private:Component *m_component; };class ConcreteDecoratorA: public Decorator{public:ConcreteDecoratorA();void Operation();private:string m_state; };class ConcreteDecoratorB: public Decorator{public:void Operation(); };class ConcreteDecoratorC: public Decorator{public:void Operation(); };#endif // !HEAD_HHead.cpp
#include "Head.h"void ConcreteComponent::Operation() {cout << "基本框架" << endl; }Decorator::Decorator() {this->m_component = nullptr; }void Decorator::setComponent(Component *component) {this->m_component = component; }void Decorator::Operation() {if(this->m_component != nullptr){m_component->Operation();} }ConcreteDecoratorA::ConcreteDecoratorA() {m_state = "组建一"; }void ConcreteDecoratorA::Operation() {Decorator::Operation();cout << m_state << endl; }void ConcreteDecoratorB::Operation() {Decorator::Operation();cout << "组建二" << endl; }void ConcreteDecoratorC::Operation() {Decorator::Operation();cout << "组建三" << endl; }main.cpp
#include "Head.h"void main(void){ConcreteComponent *c1 = new ConcreteComponent;ConcreteDecoratorA *ccdA1 = new ConcreteDecoratorA;ConcreteDecoratorB *ccdB1 = new ConcreteDecoratorB;ccdA1->setComponent(c1);ccdB1->setComponent(ccdA1);ccdB1->Operation();delete c1;delete ccdB1;delete ccdA1;cout << endl;cout << "---------------华丽的分割线---------------" << endl;ConcreteComponent *c2 = new ConcreteComponent;ConcreteDecoratorA *ccdA2 = new ConcreteDecoratorA;ConcreteDecoratorC *ccdC2 = new ConcreteDecoratorC;ccdA2->setComponent(c2);ccdC2->setComponent(ccdA2);ccdC2->Operation();delete c2;delete ccdA2;delete ccdC2;getchar(); }
Component是定义一个对象接口,可以给这些对象动态地添加职责。ConcreteComponent是定义一个具体的对象,也可以给这个对象添加一些职责。Decorator,装饰抽象类,继承了Component,从外类来扩展Component类的功能,但对Component来说,是无需知道Decorator的存在的,置于ConcreteDecorator是具体的装饰对象,起到给Component添加职责的功能
总结
以上是生活随笔为你收集整理的C++设计模式-装饰模式的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 软考系统架构师笔记-最后知识点总结(四)
- 下一篇: C++设计模式-抽象工厂模式