当前位置: 首页 > 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库&…...

Prompt Tuning、P-Tuning、Prefix Tuning的区别

一、Prompt Tuning、P-Tuning、Prefix Tuning的区别 1. Prompt Tuning(提示调优) 核心思想:固定预训练模型参数,仅学习额外的连续提示向量(通常是嵌入层的一部分)。实现方式:在输入文本前添加可训练的连续向量(软提示),模型只更新这些提示参数。优势:参数量少(仅提…...

Qt Widget类解析与代码注释

#include "widget.h" #include "ui_widget.h"Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget) {ui->setupUi(this); }Widget::~Widget() {delete ui; }//解释这串代码&#xff0c;写上注释 当然可以&#xff01;这段代码是 Qt …...

CentOS下的分布式内存计算Spark环境部署

一、Spark 核心架构与应用场景 1.1 分布式计算引擎的核心优势 Spark 是基于内存的分布式计算框架&#xff0c;相比 MapReduce 具有以下核心优势&#xff1a; 内存计算&#xff1a;数据可常驻内存&#xff0c;迭代计算性能提升 10-100 倍&#xff08;文档段落&#xff1a;3-79…...

JVM垃圾回收机制全解析

Java虚拟机&#xff08;JVM&#xff09;中的垃圾收集器&#xff08;Garbage Collector&#xff0c;简称GC&#xff09;是用于自动管理内存的机制。它负责识别和清除不再被程序使用的对象&#xff0c;从而释放内存空间&#xff0c;避免内存泄漏和内存溢出等问题。垃圾收集器在Ja…...

【Go】3、Go语言进阶与依赖管理

前言 本系列文章参考自稀土掘金上的 【字节内部课】公开课&#xff0c;做自我学习总结整理。 Go语言并发编程 Go语言原生支持并发编程&#xff0c;它的核心机制是 Goroutine 协程、Channel 通道&#xff0c;并基于CSP&#xff08;Communicating Sequential Processes&#xff0…...

vue3 定时器-定义全局方法 vue+ts

1.创建ts文件 路径&#xff1a;src/utils/timer.ts 完整代码&#xff1a; import { onUnmounted } from vuetype TimerCallback (...args: any[]) > voidexport function useGlobalTimer() {const timers: Map<number, NodeJS.Timeout> new Map()// 创建定时器con…...

k8s业务程序联调工具-KtConnect

概述 原理 工具作用是建立了一个从本地到集群的单向VPN&#xff0c;根据VPN原理&#xff0c;打通两个内网必然需要借助一个公共中继节点&#xff0c;ktconnect工具巧妙的利用k8s原生的portforward能力&#xff0c;简化了建立连接的过程&#xff0c;apiserver间接起到了中继节…...

ip子接口配置及删除

配置永久生效的子接口&#xff0c;2个IP 都可以登录你这一台服务器。重启不失效。 永久的 [应用] vi /etc/sysconfig/network-scripts/ifcfg-eth0修改文件内内容 TYPE"Ethernet" BOOTPROTO"none" NAME"eth0" DEVICE"eth0" ONBOOT&q…...

USB Over IP专用硬件的5个特点

USB over IP技术通过将USB协议数据封装在标准TCP/IP网络数据包中&#xff0c;从根本上改变了USB连接。这允许客户端通过局域网或广域网远程访问和控制物理连接到服务器的USB设备&#xff08;如专用硬件设备&#xff09;&#xff0c;从而消除了直接物理连接的需要。USB over IP的…...

Yolov8 目标检测蒸馏学习记录

yolov8系列模型蒸馏基本流程&#xff0c;代码下载&#xff1a;这里本人提交了一个demo:djdll/Yolov8_Distillation: Yolov8轻量化_蒸馏代码实现 在轻量化模型设计中&#xff0c;**知识蒸馏&#xff08;Knowledge Distillation&#xff09;**被广泛应用&#xff0c;作为提升模型…...