当前位置: 首页 > news >正文

C++设计模式-装饰器(Decorator)

目录

C++设计模式-装饰器(Decorator)

一、意图

二、适用性

三、结构

四、参与者

五、代码


C++设计模式-装饰器(Decorator)

一、意图

动态地给一个对象添加一些额外的职责。就增加功能来说,Decorator模式相比生成子类更为灵活。

二、适用性

  • 在不影响其他对象的情况下,以动态、透明的方式给单个对象添加职责。
  • 处理那些可以撤消的职责。
  • 当不能采用生成子类的方法进行扩充时。一种情况是,可能有大量独立的扩展,为支持每一种组合将产生大量的子类,使得子类数目呈爆炸性增长。另一种情况可能是因为类定义被隐藏,或类定义不能用于生成子类。

三、结构

 

四、参与者

  • Component

        定义一个对象接口,可以给这些对象动态地添加职责。

  • ConcreteDecorator

       定义一个对象,可以给这个对象添加一些职责。

  • Decorator

        维持一个指向Component对象的指针,并定义一个与Component接口一致的接口。

  • ConcreteComponent

        向组件添加职责。

五、代码

#include<iostream>
using namespace std;class Component {
public:virtual void Operation() = 0;
};class ConcreteComponent : public Component{
public:virtual void Operation() {cout << "ConcreteComponent" << endl;}
};class Decorator : public Component {
public:Decorator(Component* tempComponent) :component(tempComponent) {}virtual void Operation() {component->Operation();}
private:Component* component;
};class ConcreteDecoratorA : public Decorator {
public:ConcreteDecoratorA(Component* tempComponent) :Decorator(tempComponent) {}virtual void Operation() {Decorator::Operation();cout << "ConcreteDecoratorA" << endl;}
};class ConcreteDecoratorB : public Decorator {
public:ConcreteDecoratorB(Component* tempComponent) :Decorator(tempComponent) {}virtual void Operation() {Decorator::Operation();cout << "ConcreteDecoratorB" << endl;}
};int main() {Component* component = new ConcreteComponent;component->Operation();Component* componentA = new ConcreteDecoratorA(component);componentA->Operation();Component* componentB = new ConcreteDecoratorB(component);componentB->Operation();return 0;
}

http://www.lryc.cn/news/184798.html

相关文章:

  • 【C语言】结构类型的定义和使用
  • C++内存管理:其二、数组内存管理
  • No169.精选前端面试题,享受每天的挑战和学习
  • Hadoop设置hdfs全局指令
  • IDEA 2023.1.3图文安装教程及下载
  • 【JVM】运行时数据区(内存区域划分)详解
  • Python-Scrapy框架(框架学习)
  • flink生成水位线记录方式--基于特殊记录的水位线生成器
  • Arcgis日常天坑问题(1)——将Revit模型转为slpk数据卡住不前
  • JavaWeb:上传文件
  • STM32 大小端与字节对齐使用记录
  • RabbitMQ中basic**方法汇总与参数解释
  • linux之/etc/default/useradd文件
  • 3.primitive主数据类型和引用 认识变量
  • 【群智能算法改进】一种改进的光学显微镜算法 IOMA算法[1]【Matlab代码#60】
  • 第三课-软件升级-Stable Diffusion教程
  • 【C++】设计模式之——建造者
  • 【C++】基础语句(学习笔记)
  • 大厂秋招真题【DP】米哈游20230924秋招T2-米小游与魔法少女-奇运
  • LVS+Keepalived 高可用集群负载均衡
  • Qt QList类和QLinkedList类 详解
  • Mac安装GYM遇到的一些坑
  • 【高级rabbitmq】
  • 数百个下载能够传播 Rootkit 的恶意 NPM 软件包
  • SpringBoot的error用全局异常去处理
  • MyBatisPlus(十一)包含查询:in
  • Linux命令定位与查找:which、whereis和find的用法详解
  • LeetCode 面试题 17.10. Find Majority Element LCCI【摩尔投票法】简单
  • 多校联测11 模板题
  • Linux SSH连接远程服务器(免密登录、scp和sftp传输文件)