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

《设计模式的艺术》笔记 - 享元模式

介绍

        享元模式运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象,而这些对象都很相似,状态变化很小,可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象,因此它又称为轻量级模式,是一种对象结构型模式。

实现

myclass.h

//
// Created by yuwp on 2024/1/12.
//#ifndef DESIGNPATTERNS_MYCLASS_H
#define DESIGNPATTERNS_MYCLASS_H#include <iostream>
#include <unordered_map>class Flyweight {   // 享元抽象类
public:Flyweight(const std::string &in);virtual void operation(const std::string &out) = 0;const std::string &getMIn() const;private:std::string m_in;
};class ConcreteFlyweight : public Flyweight {    // 具体享元类
public:ConcreteFlyweight(const std::string &in);void operation(const std::string &out) override;
};class FlyweightFactory {    // 配合工厂模式使用享元工厂类
public:~FlyweightFactory();Flyweight *getFlyweight(const std::string &key);
private:std::unordered_map<std::string, Flyweight *> m_flyweights;
};#endif //DESIGNPATTERNS_MYCLASS_H

myclass.cpp

//
// Created by yuwp on 2024/1/12.
//#include "myclass.h"Flyweight::Flyweight(const std::string &in) {m_in = in;
}const std::string &Flyweight::getMIn() const {return m_in;
}ConcreteFlyweight::ConcreteFlyweight(const std::string &in) : Flyweight(in) {}void ConcreteFlyweight::operation(const std::string &out) {std::cout<< "内部状态: " << getMIn() << ", 外部状态: " << out << std::endl;
}FlyweightFactory::~FlyweightFactory() {for (auto it : m_flyweights) {if (it.second) {delete it.second;}}
}Flyweight* FlyweightFactory::getFlyweight(const std::string &key) {auto it = m_flyweights.find(key);if (it != m_flyweights.end()) {return it->second;} else {Flyweight *flyweight = new ConcreteFlyweight(key);m_flyweights.insert(std::make_pair(key, flyweight));return flyweight;}
}

main.cpp

#include <iostream>
#include <mutex>
#include "myclass.h"int main() {FlyweightFactory *factory = new FlyweightFactory();auto fly1 = factory->getFlyweight("a");auto fly2 = factory->getFlyweight("b");auto fly3 = factory->getFlyweight("a");fly1->operation("1");fly2->operation("2");fly3->operation("3");delete factory;return 0;
}

总结

优点

        1. 可以极大减少内存中对象的数量,使得相同或相似对象在内存中只保存一份,从而可以节约系统资源,提高系统性能。

        2. 享元模式的外部状态相对独立,而且不会影响其内部状态,从而使得享元对象可以在不同的环境中被共享。

缺点

        1. 享元模式需要分离出内部状态和外部状态,从而使得系统变得复杂,这使得程序的逻辑复杂化。

        2. 为了使对象可以共享,享元模式需要将享元对象的部分状态外部化,而读取外部状态将使得运行时间变长。

适用场景

        1. 一个系统有大量相同或者相似的对象,造成内存的大量耗费。

        2. 对象的大部分状态都可以外部化,可以将这些外部状态传入对象中。

        3. 在使用享元模式时需要维护一个存储享元对象的享元池,而这需要耗费一定的系统资源。因此,在需要多次重复使用同一享元对象时才值得使用享元模式。

练习

myclass.h

//
// Created by yuwp on 2024/1/12.
//#ifndef DESIGNPATTERNS_MYCLASS_H
#define DESIGNPATTERNS_MYCLASS_H#include <iostream>
#include <unordered_map>class Flyweight {   // 享元抽象类
public:Flyweight(const std::string &in);virtual void display(const std::string &out) = 0;const std::string &getMIn() const;private:std::string m_in;
};class PictureFlyweight : public Flyweight {    // 具体享元类
public:PictureFlyweight(const std::string &in);void display(const std::string &out) override;
};class AnimationFlyweight : public Flyweight {    // 具体享元类
public:AnimationFlyweight(const std::string &in);void display(const std::string &out) override;
};class VideoFlyweight : public Flyweight {    // 具体享元类
public:VideoFlyweight(const std::string &in);void display(const std::string &out) override;
};class FlyweightFactory {    // 配合工厂模式使用享元工厂类
public:~FlyweightFactory();Flyweight *getFlyweight(const std::string &key);static FlyweightFactory *getInstance();
private:FlyweightFactory();std::unordered_map<std::string, Flyweight *> m_flyweights;
};#endif //DESIGNPATTERNS_MYCLASS_H

myclass.cpp

//
// Created by yuwp on 2024/1/12.
//#include "myclass.h"Flyweight::Flyweight(const std::string &in) {m_in = in;
}const std::string &Flyweight::getMIn() const {return m_in;
}PictureFlyweight::PictureFlyweight(const std::string &in) : Flyweight(in) {}void PictureFlyweight::display(const std::string &out) {std::cout << out << ", " << getMIn() << std::endl;
}AnimationFlyweight::AnimationFlyweight(const std::string &in) : Flyweight(in) {}void AnimationFlyweight::display(const std::string &out) {std::cout << out << ", " << getMIn() << std::endl;
}VideoFlyweight::VideoFlyweight(const std::string &in) : Flyweight(in) {}void VideoFlyweight::display(const std::string &out) {std::cout << out << ", " << getMIn() << std::endl;
}FlyweightFactory::FlyweightFactory() {}FlyweightFactory* FlyweightFactory::getInstance() {static FlyweightFactory *factory = new FlyweightFactory();return factory;
}FlyweightFactory::~FlyweightFactory() {for (auto it : m_flyweights) {if (it.second) {delete it.second;}}
}Flyweight* FlyweightFactory::getFlyweight(const std::string &key) {auto it = m_flyweights.find(key);if (it != m_flyweights.end()) {return it->second;} else {Flyweight *flyweight = nullptr;if (key == "图片") {flyweight = new PictureFlyweight(key);} else if (key == "动画") {flyweight = new AnimationFlyweight(key);} else if (key == "视频") {flyweight = new VideoFlyweight(key);}m_flyweights.insert(std::make_pair(key, flyweight));return flyweight;}
}

main.cpp

#include <iostream>
#include <mutex>
#include "myclass.h"int main() {FlyweightFactory *factory = FlyweightFactory::getInstance();factory->getFlyweight("图片")->display("1");factory->getFlyweight("动画")->display("2");factory->getFlyweight("视频")->display("3");factory->getFlyweight("图片")->display("4");return 0;
}

相关文章:

《设计模式的艺术》笔记 - 享元模式

介绍 享元模式运用共享技术有效地支持大量细粒度对象的复用。系统只使用少量的对象&#xff0c;而这些对象都很相似&#xff0c;状态变化很小&#xff0c;可以实现对象的多次复用。由于享元模式要求能够共享的对象必须是细粒度对象&#xff0c;因此它又称为轻量级模式&#xff…...

ubuntu系统(10):使用samba共享linux主机中文件

目录 一、samba安装步骤 1、Linux主机端操作 &#xff08;1&#xff09;安装sabma &#xff08;2&#xff09;修改samba配置文件 &#xff08;3&#xff09;为user_name用户设置samba访问的密码 &#xff08;4&#xff09;重启samba服务 2、Windows端 二、使用 1、代码…...

数据集成时表模型同步方法解析

01 背景介绍 数据治理的第一步&#xff0c;也是数据中台的一个基础功能 — 即将来自各类业务数据源的数据&#xff0c;同步集成至中台 ODS 层。业务数据源多种多样&#xff0c;单单可能涉及到的主流关系型数据库就有近十种。功能更加全面的数据中台通常还具有对接非关系型数据…...

彻底解决charles抓包https乱码的问题

最近做js逆向&#xff0c;听说charles比浏览器抓包更好用&#xff0c;结果发现全是乱码&#xff0c;根本没法用。 然后查询网上水文&#xff1a;全部都是装证书&#xff0c;根本没用&#xff01; 最后终于找到解决办法&#xff0c;在这里记录一下&#xff1a; 乱码的根本原因…...

Towards Robust Blind Face Restoration with Codebook Lookup Transformer

Towards Real World Blind Face Restoration with Generative Facial Prior 这个projec相对codeformer已经是老一些的了&#xff0c;CodeFormer paper说自己的效果比这个更好。 有看了这个视频&#xff0c;它借用了R-ESRGAN 4x 和 GFPGAN 50%&#xff0c;既保留了一些人物特征…...

flutter3使用dio库发送FormData数据格式时候的坑,和get库冲突解决办法

问题描述 问题1&#xff1a;当你使用FormData.from(Flutter3直接不能用)的时候&#xff0c;可能会提示没有这个方法&#xff0c;或者使用FormData.fromMap(flutter3的dio支持)的时候也提示没有&#xff0c;这时候可能就是和get库里面的Formdata冲突了 问题1&#xff1a;The me…...

matlab读取pwm波数据,不用timer的方法,这里可以参考。Matlab/Simulink之STM32开发-编码器测速

这里提供了一个不用timer的方法&#xff0c;可以参考&#xff1a; https://blog.csdn.net/weixin_36967309/article/details/88699830 Matlab/Simulink之STM32开发-编码器测速...

使用 Python 创造你自己的计算机游戏(游戏编程快速上手)第四版:第十九章到第二十一章

十九、碰撞检测 原文&#xff1a;inventwithpython.com/invent4thed/chapter19.html 译者&#xff1a;飞龙 协议&#xff1a;CC BY-NC-SA 4.0 碰撞检测涉及确定屏幕上的两个物体何时相互接触&#xff08;即发生碰撞&#xff09;。碰撞检测对于游戏非常有用。例如&#xff0c;如…...

Multimodal Multitask Learning with a Unified Transformer

SNLI-VE dataset&#xff0c;natural language understanding tasks&#xff1a;MNLI&#xff0c;QNLI&#xff0c;QQP&#xff0c;SST-2 截止到发文时间的issue数&#xff0c;多吓人呐&#xff0c;不建议复现...

c指针和字符数组初学者比较好的例子

本练习的主题&#xff1a;一个对象的指针可以修改这个对象的内容&#xff1b; 注&#xff1a;对象是指一个固定大小的内存块。 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> int getMem(char **p1,int *m…...

微信原生小程序上传与识别以及监听多个checkbox事件打开pdf

1.点击上传并识别 组件样式<van-field border"{{ false }}" placeholder"请输入银行卡卡号" model:value"{{bankNo}}" label"卡号"><van-icon bindtap"handleChooseImg" slot"right-icon" name"sca…...

关于C#中Monitor的wait/pulse的理解

wait&#xff1a;表示释放对象上的锁并阻止当前线程&#xff0c;直到它重新获取该锁。 pulse&#xff1a;表示通知等待队列中的线程锁定对象状态的更改。 当线程调用 Wait 时&#xff0c;它会释放对象上的锁并进入对象的等待队列。 对象的就绪队列中的下一个线程 (如果有一个…...

LeetCode 2894. 分类求和并作差

给你两个正整数 n 和 m 。 现定义两个整数 num1 和 num2 &#xff0c;如下所示&#xff1a; num1&#xff1a;范围 [1, n] 内所有 无法被 m 整除 的整数之和。 num2&#xff1a;范围 [1, n] 内所有 能够被 m 整除 的整数之和。 返回整数 num1 - num2 。 示例 1&#xff1a; …...

PLSQL 把多个字段转为json格式

PLSQL 把多个字段转为json格式 sql Select cc.bm, cc.xm, json_arrayagg(cc.hb) jgFrom (Select aa.bm, aa.xm, json_object(aa.ksbh, aa.wjmc) hbFrom (Select 001 bm, 老六 xm, 0001 ksbh, 文具盒 wjmcFrom dual tUnion AllSelect 001 bm, 老六 xm, 0002 ksbh, 毛笔 wjmcFr…...

国内环境 GitHub 拉取仓库速度慢的缓解方案

第一步&#xff1a; 浏览器打开如下两个网址&#xff0c;找到对应 IP 地址&#xff1a; GitHub.com - GitHub: Lets build from here GitHubgithub.global.ssl.fastly.net 假设对应 IP 地址分别为 140.82.xx.xxx 和 199.232.yy.yyy 第二步&#xff1a; 编辑 hosts 文件 sud…...

设计模式⑥ :访问数据结构

文章目录 一、前言二、Visitor 模式1. 介绍2. 应用3. 总结 三、Chain of Responsibility 模式1. 介绍2. 应用3. 总结 参考内容 一、前言 有时候不想动脑子&#xff0c;就懒得看源码又不像浪费时间所以会看看书&#xff0c;但是又记不住&#xff0c;所以决定开始写"抄书&q…...

无法打开浏览器开发者工具的可能解决方法

网页地址: https://jx.xyflv.cc/?url视频地址url 我在抖音里面抓了一个视频地址, 获取到响应的json数据, 找到里面的视频地址信息 这个网站很好用: https://www.jsont.run/ 可以使用js语法对json对象操作, 找到所有视频的url地址 打开网页: https://jx.xyflv.cc/?urlhttps:…...

Android ANR 总结

工作之余&#xff0c;对之前学习到的和结合自己项目过程中的遇到的问题经验做一些总结&#xff0c;下面讲一讲Android开发过程中遇到的ANR的问题&#xff0c;做一下整理 一、概述 解决ANR一直是Android 开发者需要掌握的重要技巧&#xff0c;一般从三个方面着手。 开发阶段&a…...

群晖Drive搭建云同步服务器结合内网穿透实现Obsidian笔记文件远程多端同步

文章目录 一、简介软件特色演示&#xff1a; 二、使用免费群晖虚拟机搭建群晖Synology Drive服务&#xff0c;实现局域网同步1 安装并设置Synology Drive套件2 局域网内同步文件测试 三、内网穿透群晖Synology Drive&#xff0c;实现异地多端同步Windows 安装 Cpolar步骤&#…...

Flutter中的图片查看器:使用photo_view库

在移动应用开发中&#xff0c;图片查看器是一个常见的需求。Flutter提供了许多库来简化这一过程&#xff0c;其中photo_view库是一个强大而灵活的选择。本文将介绍photo_view库的基本概念以及如何在Flutter应用中使用它来实现漂亮的图片查看体验。 1. 什么是photo_view库&…...

KubeSphere 容器平台高可用:环境搭建与可视化操作指南

Linux_k8s篇 欢迎来到Linux的世界&#xff0c;看笔记好好学多敲多打&#xff0c;每个人都是大神&#xff01; 题目&#xff1a;KubeSphere 容器平台高可用&#xff1a;环境搭建与可视化操作指南 版本号: 1.0,0 作者: 老王要学习 日期: 2025.06.05 适用环境: Ubuntu22 文档说…...

SpringCloudGateway 自定义局部过滤器

场景&#xff1a; 将所有请求转化为同一路径请求&#xff08;方便穿网配置&#xff09;在请求头内标识原来路径&#xff0c;然后在将请求分发给不同服务 AllToOneGatewayFilterFactory import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; impor…...

2025季度云服务器排行榜

在全球云服务器市场&#xff0c;各厂商的排名和地位并非一成不变&#xff0c;而是由其独特的优势、战略布局和市场适应性共同决定的。以下是根据2025年市场趋势&#xff0c;对主要云服务器厂商在排行榜中占据重要位置的原因和优势进行深度分析&#xff1a; 一、全球“三巨头”…...

AI病理诊断七剑下天山,医疗未来触手可及

一、病理诊断困局&#xff1a;刀尖上的医学艺术 1.1 金标准背后的隐痛 病理诊断被誉为"诊断的诊断"&#xff0c;医生需通过显微镜观察组织切片&#xff0c;在细胞迷宫中捕捉癌变信号。某省病理质控报告显示&#xff0c;基层医院误诊率达12%-15%&#xff0c;专家会诊…...

纯 Java 项目(非 SpringBoot)集成 Mybatis-Plus 和 Mybatis-Plus-Join

纯 Java 项目&#xff08;非 SpringBoot&#xff09;集成 Mybatis-Plus 和 Mybatis-Plus-Join 1、依赖1.1、依赖版本1.2、pom.xml 2、代码2.1、SqlSession 构造器2.2、MybatisPlus代码生成器2.3、获取 config.yml 配置2.3.1、config.yml2.3.2、项目配置类 2.4、ftl 模板2.4.1、…...

LabVIEW双光子成像系统技术

双光子成像技术的核心特性 双光子成像通过双低能量光子协同激发机制&#xff0c;展现出显著的技术优势&#xff1a; 深层组织穿透能力&#xff1a;适用于活体组织深度成像 高分辨率观测性能&#xff1a;满足微观结构的精细研究需求 低光毒性特点&#xff1a;减少对样本的损伤…...

Spring AI Chat Memory 实战指南:Local 与 JDBC 存储集成

一个面向 Java 开发者的 Sring-Ai 示例工程项目&#xff0c;该项目是一个 Spring AI 快速入门的样例工程项目&#xff0c;旨在通过一些小的案例展示 Spring AI 框架的核心功能和使用方法。 项目采用模块化设计&#xff0c;每个模块都专注于特定的功能领域&#xff0c;便于学习和…...

数据结构:递归的种类(Types of Recursion)

目录 尾递归&#xff08;Tail Recursion&#xff09; 什么是 Loop&#xff08;循环&#xff09;&#xff1f; 复杂度分析 头递归&#xff08;Head Recursion&#xff09; 树形递归&#xff08;Tree Recursion&#xff09; 线性递归&#xff08;Linear Recursion&#xff09;…...

uni-app学习笔记三十五--扩展组件的安装和使用

由于内置组件不能满足日常开发需要&#xff0c;uniapp官方也提供了众多的扩展组件供我们使用。由于不是内置组件&#xff0c;需要安装才能使用。 一、安装扩展插件 安装方法&#xff1a; 1.访问uniapp官方文档组件部分&#xff1a;组件使用的入门教程 | uni-app官网 点击左侧…...

负载均衡器》》LVS、Nginx、HAproxy 区别

虚拟主机 先4&#xff0c;后7...