设计模式--享元模式和组合模式

享元模式

享元模式(Flyweight Pattern)又称为轻量模式,是对象池的一种实现。类似于线程池,线程池可以避免不停的创建和销毁多个对象,销毁性能。提供了减少对象数量从而改善应用所需的对象结构的方式。其宗旨是共享细粒度对象,将多个对同一对象的访问集中起来,不必为每个访问者创建一个单独的对象,以此来降低内存的消耗,属于结构型模式。

应用场景:

  1. 常常应用于系统底层的开发,以便解决系统的性能问题。
  2. 系统有大量相似对象,需要缓存池的场景。

利用缓存机制实现享元模式: 

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;interface ITicket{void showInfo(String bunk);
}class TrainTicket implements ITicket{private String from;private String to;private int price;public TrainTicket(String from, String to) {this.from = from;this.to = to;}@Overridepublic void showInfo(String bunk) {this.price = new Random().nextInt(500);System.out.println(String.format("%s->%s: %s价格: %s 元",this.from,this.to,bunk,this.price));}
}class TicketFactory{private static Map<String,ITicket> sTicketPool = new ConcurrentHashMap<>();public static ITicket queryTicket(String from, String to){String key = from + "->" + to;if(TicketFactory.sTicketPool.containsKey(key)){System.out.println("使用缓存:"+ key);return TicketFactory.sTicketPool.get(key);}System.out.println("首次查询,创建对象:" + key);ITicket ticket = new TrainTicket(from, to);TicketFactory.sTicketPool.put(key,ticket);return ticket;}}

JDK中Integer类型使用了享元模式,例如:。在Java中-128到127之间的数据在int范围类是直接从缓存中取值的。

public class Test {public static void main(String[] args) {Integer a = Integer.valueOf(100);Integer b = 100;Integer c = Integer.valueOf(1000);Integer d = 1000;System.out.println(a==b); //trueSystem.out.println(b==d); //false}
}

组合模式 

组合模式(Composite Pattern)也称为整体-部分模式,它的宗旨是通过将单个对象和组合对象用相同的接口进行表示,使得客户对单个对象和组合对象的使用具有一致性,属于结构型模式。

组合关系和聚合关系的区别:

  1. 组合关系:一只狗可以生多只小狗,但每只小狗只有一个妈妈(具有相同的生命周期)。
  2. 聚合关系:一个老师有很多学生,但每个学生又有多个老师(具有不同的生命周期)。

透明组合模式的写法:透明组合模式把所有的公共方法都定义在Component中,这样做的好处是客户端无需分辨是叶子节点和树枝节点,它们具备完全一致性的接口;缺点是叶子节点得到一些它所不需要的方法,这与设计模式 接口隔离相违背。

import lombok.Data;import java.util.ArrayList;
import java.util.List;abstract class CourseComponent{public void addChild(CourseComponent catalogComponent){throw new UnsupportedOperationException("不支持添加操作");}public void removeChild(CourseComponent catalogComponent){throw new UnsupportedOperationException("不支持删除操作");}public String getName(CourseComponent catalogComponent){throw new UnsupportedOperationException("不支持获取名称操作");}public double getPrice(CourseComponent catalogComponent){throw new UnsupportedOperationException("不支持获取价格操作");}public void print(){throw new UnsupportedOperationException("不支持打印操作");}
}@Data
class Course extends CourseComponent{private String name;private double price;public Course(String name, double price) {this.name = name;this.price = price;}@Overridepublic void print() {System.out.println(name + "(¥" + price + "元)");}
}class CoursePackage extends CourseComponent{private List<CourseComponent> items = new ArrayList<>();private String name;private Integer level;public CoursePackage(String name, Integer level) {this.name = name;this.level = level;}@Overridepublic void addChild(CourseComponent catalogComponent) {items.add(catalogComponent);}@Overridepublic String getName(CourseComponent catalogComponent) {return this.name;}@Overridepublic void removeChild(CourseComponent catalogComponent) {items.remove(catalogComponent);}@Overridepublic void print() {System.out.println(this.name);for (CourseComponent catalogComponent : items){if(this.level != null){for(int i=0;i<this.level;i++){System.out.print(" ");}for(int i=0;i<this.level;i++){System.out.print("-");}}catalogComponent.print();}}
}public class Test {public static void main(String[] args) {System.out.println("=========透明组合模式==========");CourseComponent javaBase = new Course("Java入门",8200);CourseComponent ai = new Course("人工智能",5000);CourseComponent packageCourse = new CoursePackage("Java架构师",2);CourseComponent design = new Course("设计模式",1500);packageCourse.addChild(design);CourseComponent catalog = new CoursePackage("课程主目录",1);catalog.addChild(javaBase);catalog.addChild(ai);catalog.addChild(packageCourse);catalog.print();}
}

安全组合模式的写法:好处是接口定义职责清晰,符合设计模式单一职责原则和接口隔离原则;缺点是客户需要区分树枝节点和叶子节点,客户端无法依赖抽象,违背了设计模式依赖倒置原则。

import lombok.Data;import java.util.ArrayList;
import java.util.List;abstract class CourseComponent{public void print(){throw new UnsupportedOperationException("不支持打印操作");}
}@Data
class Course extends CourseComponent{private String name;private double price;public Course(String name, double price) {this.name = name;this.price = price;}@Overridepublic void print() {System.out.println(name + "(¥" + price + "元)");}
}class CoursePackage extends CourseComponent{private List<CourseComponent> items = new ArrayList<>();private String name;private Integer level;public CoursePackage(String name, Integer level) {this.name = name;this.level = level;}public void addChild(CourseComponent catalogComponent) {items.add(catalogComponent);}public String getName(CourseComponent catalogComponent) {return this.name;}public void removeChild(CourseComponent catalogComponent) {items.remove(catalogComponent);}@Overridepublic void print() {System.out.println(this.name);for (CourseComponent catalogComponent : items){if(this.level != null){for(int i=0;i<this.level;i++){System.out.print(" ");}for(int i=0;i<this.level;i++){System.out.print("-");}}catalogComponent.print();}}
}public class Test {public static void main(String[] args) {System.out.println("=========透明组合模式==========");CourseComponent javaBase = new Course("Java入门",8200);CourseComponent ai = new Course("人工智能",5000);CoursePackage packageCourse = new CoursePackage("Java架构师",2);CourseComponent design = new Course("设计模式",1500);packageCourse.addChild(design);CoursePackage catalog = new CoursePackage("课程主目录",1);catalog.addChild(javaBase);catalog.addChild(ai);catalog.addChild(packageCourse);catalog.print();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/703386.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

卷积神经网络 CNN

目录 卷积网络与传统网络的区别 参数共享 卷积神经网络整体架构 卷积操作的作用 卷积核的定义 卷积特征值计算方法 卷积层涉及的参数 边缘填充 ​编辑 卷积结果计算 池化层 整体网格架构 VGG网络架构 残差网络Resnet 卷积网络与传统网络的区别 卷积神经网络&#x…

50.仿简道云公式函数实战-文本函数-ISEMPTY

1. ISEMPTY函数 判断值是否为空字符串、空对象或者空数组。 支持使用 ISEMPTY 函数的字段有&#xff1a;单行文本、多行文本、数字、日期时间、单选按钮组、复选框组、下拉框、下拉复选框、地址、定位、成员字段、部门字段、微信昵称、微信 OpenID、扩展字段。 2. 函数用法 …

API保障——电子商务安全性与稳定性设计

在这次深入探讨中&#xff0c;我们将深入了解API设计&#xff0c;从基础知识开始&#xff0c;逐步进阶到定义出色API的最佳实践。 作为开发者&#xff0c;你可能对许多这些概念很熟悉&#xff0c;但我将提供详细的解释&#xff0c;以加深你的理解。 ​ API设计&#xff1a;电…

19.openeuler OECA认证模拟题2

单选 1、()命令用于查看系统所有磁盘的信息,包括已挂载和未挂载磁盘。A A、fdisk -l B、su -I C、du -I D、free -i 2、在Linux中,通过设备名来访问设备,设备名存放在()目录中。D A、/etc B、/opt C、/root D、/dev 3、通过修改以下哪个配置文件可以实现

Linux 文件权限详细教程

目录 前言 查看文件权限 修改文件权限 符号方式 数字方式 前言 Linux 文件权限是系统中非常重要的概念之一&#xff0c;用于控制对文件和目录的访问。权限分为读&#xff08;Read&#xff09;、写&#xff08;Write&#xff09;、执行&#xff08;Execute&#xff09;三个…

Android Jni的介绍和简单Demo实现

Android Jni的介绍和简单Demo实现 文章目录 Android Jni的介绍和简单Demo实现一、JNI的简单介绍JNINDKJni的开发背景&#xff1a;**JNI在 Android 开发里的主要应用场景&#xff1a;** 二、JNI的简单Demo1、Demo主要界面和效果展示2、CMake编译加载文件add_library 指令的加载库…

将 lfslivecd-x86-6.3-r2145.iso 放入 PC中的 U盘做启动U盘

基于 LFS-6.3 将 系统放入 虚拟机中的 U盘 中讲述了 将 制作好的 LFS-6.3 放入 虚拟机的U盘,但是该U盘不能在PC启动.所以要 研究一下 将 制作好的 LFS-6.3 放入 PC的U盘,在做这个之前,要做一个 将 lfslivecd-x86-6.3-r2145.iso 放入 PC的U盘 将 lfslivecd-x86-6.3-r2145.iso 放…

力扣--双指针167.二数之和Ⅱ

这题一个穷举方法是比较好想到的&#xff1a; class Solution { public:vector<int> twoSum(vector<int>& numbers, int target) {int i,j;int nnumbers.size();vector<int>result(2,0);for(i0;i<n-1;i){for(ji1;j<n;j){if(numbers[i]numbers[j…

分库分表如何管理不同实例中几万张分片表?

大家好&#xff0c;我是小富&#xff5e; ShardingSphere实现分库分表&#xff0c;如何管理分布在不同数据库实例中的成千上万张分片表&#xff1f; 上边的问题是之前有个小伙伴看了我的分库分表的文章&#xff0c;私下咨询我的&#xff0c;看到他的提问我第一感觉就是这老铁…

《高质量的C/C++编程规范》学习

目录 一、编程规范基础知识 1、头文件 2、程序的板式风格 3、命名规则 二、表达式和基本语句 1、运算符的优先级 2、复合表达式 3、if语句 4、循环语句的效率 5、for循环语句 6、switch语句 三、常量 1、#define和const比较 2、常量定义规则 四、函数设计 1、参…

【k8s资源调度-Deployment】

1、标签和选择器 1.1 标签Label 配置文件&#xff1a;在各类资源的sepc.metadata.label 中进行配置通过kubectl 命令行创建修改标签&#xff0c;语法如下 创建临时label&#xff1a;kubectl label po <资源名称> apphello -n <命令空间&#xff08;可不加&#xff0…

如何在uniapp中实现二维码生成功能

官方文档&#xff1a;https://uqrcode.cn/doc。 github地址&#xff1a;https://github.com/Sansnn/uQRCode。 npm地址&#xff1a;https://www.npmjs.com/package/uqrcodejs。 uni-app插件市场地址&#xff1a;https://ext.dcloud.net.cn/plugin?id1287 <canvas canvas-id…

2024生物科学、医学技术与化学国际会议(ICBSMTC2024)

2024生物科学、医学技术与化学国际会议(ICBSMTC2024) 会议简介 ICBSMTC2024是一个聚焦于生物科学、医学技术与化学领域的学术交流活动&#xff0c;会议将在中国桂林举行&#xff0c;会议旨在促进相关领域的学术交流与发展。会议将汇集来自世界各地的顶级学者和专家&#xf…

ChatGpt大模型入门

环境配置 创建虚拟环境 建议创建一个新的虚拟环境&#xff0c;避免安装依赖冲突&#xff0c; conda下载&#xff1a; https://docs.conda.io/en/latest/miniconda.html conda安装&#xff1a; https://zhuanlan.zhihu.com/p/591091259 或者使用venv 使用参考&#xff1a;http…

人工智能_CPU微调ChatGLM大模型_使用P-Tuning v2进行大模型微调_007_微调_002---人工智能工作笔记0102

这里我们先试着训练一下,我们用官方提供的训练数据进行训练. 也没有说使用CPU可以进行微调,但是我们先执行一下试试: https://www.heywhale.com/mw/project/6436d82948f7da1fee2be59e 可以看到说INT4量化级别最低需要7GB显存可以启动微调,但是 并没有说CPU可以进行微调.我们…

docker 安装minio 一脚shell脚本

要创建一个用于安装Minio的Docker的Shell脚本&#xff0c;你可以按照以下步骤进行。这个脚本会执行以下操作&#xff1a; 拉取Minio的Docker镜像。创建一个Docker容器并映射端口。设置Minio的访问密钥和秘密密钥。持久化存储数据到本地目录。 以下是一个简单的Shell脚本示例&…

【b站咸虾米】chapter5_uniapp-API_新课uniapp零基础入门到项目打包(微信小程序/H5/vue/安卓apk)全掌握

课程地址&#xff1a;【新课uniapp零基础入门到项目打包&#xff08;微信小程序/H5/vue/安卓apk&#xff09;全掌握】 https://www.bilibili.com/video/BV1mT411K7nW/?p12&share_sourcecopy_web&vd_sourceb1cb921b73fe3808550eaf2224d1c155 目录 5 API 5.1 页面和路…

el-input限制输入正整数

el-input框是Element UI库中的一个输入框组件&#xff0c;用于接收用户的输入。如果你想限制el-input框只能输入数字&#xff0c;可以通过以下两种方式实现&#xff1a; 一,使用type属性&#xff1a;将el-input的type属性设置为"number"&#xff0c;这将强制输入框只…

Linux 文件操作

目录 C语言下的文件操作 Linux下的文件操作 文件描述符的前因后果 文件描述符的概念 文件描述符的分配规则 理解C语言的FILE结构体 Linux重定向 文件缓冲区 文件系统 文件系统的概念 ext2文件系统 对ext2的补充 虚拟文件系统的概念 软硬链接 C语言下的文件操作 …

备战蓝桥杯---基础算法刷题2

题目有一点水&#xff0c;不过还是有几个好题的&#xff0c;我在这分享一下&#xff1a; 很容易想到先往最高处跳再往最低处跳&#xff0c;依次类推&#xff0c;那怎么保证其正确性呢&#xff1f; 证法1. 在此&#xff0c;我们从0开始&#xff0c;假设可以跳到a,b,c(a<b<…