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

设计模式-04-原型模式

       经典的设计模式有23种,但是常用的设计模式一般情况下不会到一半,我们就针对一些常用的设计模式进行一些详细的讲解和分析,方便大家更加容易理解和使用设计模式。

1-什么是原型模式

       如果对象的创建成本比较大,而同一个类的不同对象之间差别不大(大部分字段都相同),在这种情况下,我们可以利用对已有对象(原型)进行复制(或者叫拷贝)的方式,来创建新对象,以达到节省创建时间的目的。这种基于原型来创建对象的方式就叫作原型设计模式,简称原型模式。

2-原型模式的应用

       需求:假设数据库中存储了大约10万条“搜索关键词”信息,每条信息包含关键词名称、关键词被搜索的次数、信息最近被更新的时间等。系统A在启动的时候会加载这份数据到内存中,用于处理某些其他的业务需求。为了方便快速地查找某个关键词对应的信息,我们给关键词建立一个hashmap,其中key=关键词名称,value就是 关键词对象(包括名称,检索次数,更新时间)。

       另外一个系统B,专门用来分析搜索日志,定期(比如间隔10分钟)批量地更新数据库中的数据,并且标记为新的数据版本(更新时会把更新时间变成当前时间)。这里我们假设只有更新和新添关键词,没有删除关键词的行为。

       为了保证系统A中数据的实时性(不一定非常实时,但数据也不能太旧),系统A需要定期根据数据库中的数据,更新内存中的索引和数据。

public class Demo {private ConcurrentHashMap<String, SearchWord> currentKeywords = new ConcurrentHashMap<>();private long lastUpdateTime = -1;public void refresh() {// 从数据库中取出更新时间>lastUpdateTime的数据,放入到currentKeywords中List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);long maxNewUpdatedTime = lastUpdateTime;for (SearchWord searchWord : toBeUpdatedSearchWords) {if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {maxNewUpdatedTime = searchWord.getLastUpdateTime();}if (currentKeywords.containsKey(searchWord.getKeyword())) {currentKeywords.replace(searchWord.getKeyword(), searchWord);} else {currentKeywords.put(searchWord.getKeyword(), searchWord);}}lastUpdateTime = maxNewUpdatedTime;}private List<SearchWord> getSearchWords(long lastUpdateTime) {// TODO: 从数据库中取出更新时间>lastUpdateTime的数据return null;}

       现在我们有一个特殊的需求:任何时刻,系统A中的所有数据都必须是同一个版本的,要么都是版本a,要么都是版本b,不能有的是版本a,有的是版本b。那刚刚的更新方式就不能满足这个要求了。除此之外,我们还要求:在更新内存数据的时候,系统A不能处于不可用状态,也就是不能停机更新数据。

      实际上,也不难。我们把正在使用的数据的版本定义为“服务版本”,当我们要更新内存中的数据的时候,我们并不是直接在服务版本(假设是版本a数据)上更新,而是重新创建另一个版本数据(假设是版本b数据),等新的版本数据建好之后,再一次性地将服务版本从版本a切换到版本b。这样既保证了数据一直可用,又避免了中间状态的存在。

public class Demo {private HashMap<String, SearchWord> currentKeywords=new HashMap<>();public void refresh() {HashMap<String, SearchWord> newKeywords = new LinkedHashMap<>();// 从数据库中取出所有的数据,放入到newKeywords中List<SearchWord> toBeUpdatedSearchWords = getSearchWords();for (SearchWord searchWord : toBeUpdatedSearchWords) {newKeywords.put(searchWord.getKeyword(), searchWord);}currentKeywords = newKeywords;}private List<SearchWord> getSearchWords() {// TODO: 从数据库中取出所有的数据return null;}
}

       在上面的代码实现中,newKeywords构建的成本比较高。我们需要将这10万条数据从数据库中读出,然后计算哈希值,构建newKeywords。这个过程显然是比较耗时。为了提高效率,原型模式就派上用场了。

       思路:我们拷贝currentKeywords数据到newKeywords中,然后从数据库中只捞出新增或者有更新的关键词,更新到newKeywords中。而相对于10万条数据来说,每次新增或者更新的关键词个数是比较少的,所以,这种策略大大提高了数据更新的效率。

public class Demo {private HashMap<String, SearchWord> currentKeywords=new HashMap<>();private long lastUpdateTime = -1;public void refresh() {// 原型模式就这么简单,拷贝已有对象的数据,更新少量差值HashMap<String, SearchWord> newKeywords = (HashMap<String, SearchWord>) currentKeywords.clone();// 从数据库中取出更新时间>lastUpdateTime的数据,放入到newKeywords中List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);long maxNewUpdatedTime = lastUpdateTime;for (SearchWord searchWord : toBeUpdatedSearchWords) {if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {maxNewUpdatedTime = searchWord.getLastUpdateTime();}if (newKeywords.containsKey(searchWord.getKeyword())) {SearchWord oldSearchWord = newKeywords.get(searchWord.getKeyword());oldSearchWord.setCount(searchWord.getCount());oldSearchWord.setLastUpdateTime(searchWord.getLastUpdateTime());} else {newKeywords.put(searchWord.getKeyword(), searchWord);}}lastUpdateTime = maxNewUpdatedTime;currentKeywords = newKeywords;}private List<SearchWord> getSearchWords(long lastUpdateTime) {// TODO: 从数据库中取出更新时间>lastUpdateTime的数据return null;}

       这里我们利用了Java中的clone()语法来复制一个对象。如果你熟悉的语言没有这个语法,那把数据从currentKeywords中一个个取出来,然后再重新计算哈希值,放入到newKeywords中也是可以接受的。毕竟,最耗时的还是从数据库中取数据的操作。相对于数据库的IO操作来说,内存操作和CPU计算的耗时都是可以忽略的。

3-深拷贝和浅拷贝

        浅拷贝只会复制图中的索引(散列表),不会复制数据(SearchWord对象)本身。相反,深拷贝不仅仅会复制索引,还会复制数据本身。浅拷贝得到的对象(newKeywords)跟原始对象(currentKeywords)共享数据(SearchWord对象),而深拷贝得到的是一份完完全全独立的对象。

       在Java语言中,Object类的clone()方法执行的就是我们刚刚说的浅拷贝。它只会拷贝对象中的基本数据类型的数据(比如,int、long),以及引用对象(SearchWord)的内存地址,不会递归地拷贝引用对象本身。

       在上面的代码中,我们通过调用HashMap上的clone()浅拷贝方法来实现原型模式。当我们通过newKeywords更新SearchWord对象的时候(比如,更新“设计模式”这个搜索关键词的访问次数),newKeywords和currentKeywords因为指向相同的一组SearchWord对象,就会导致currentKeywords中指向的SearchWord,有的是老版本的,有的是新版本的,就没法满足我们之前的需求:currentKeywords中的数据在任何时刻都是同一个版本的,不存在介于老版本与新版本之间的中间状态。

如何实现深拷贝

第一种方法:递归拷贝对象、对象的引用对象以及引用对象的引用对象……直到要拷贝的对象只包含基本数据类型数据,没有引用对象为止。

第二种方法:先将对象序列化,然后再反序列化成新的对象。

       我们可以先采用浅拷贝的方式创建newKeywords。对于需要更新的SearchWord对象,我们再使用深度拷贝的方式创建一份新的对象,替换newKeywords中的老对象。毕竟需要更新的数据是很少的。这种方式即利用了浅拷贝节省时间、空间的优点,又能保证currentKeywords中的中数据都是老版本的数据。具体的代码实现如下所示。这也是标题中讲到的,在我们这个应用场景下,最快速clone散列表的方式

public class Demo {private HashMap<String, SearchWord> currentKeywords=new HashMap<>();private long lastUpdateTime = -1;public void refresh() {// Shallow copyHashMap<String, SearchWord> newKeywords = (HashMap<String, SearchWord>) currentKeywords.clone();// 从数据库中取出更新时间>lastUpdateTime的数据,放入到newKeywords中List<SearchWord> toBeUpdatedSearchWords = getSearchWords(lastUpdateTime);long maxNewUpdatedTime = lastUpdateTime;for (SearchWord searchWord : toBeUpdatedSearchWords) {if (searchWord.getLastUpdateTime() > maxNewUpdatedTime) {maxNewUpdatedTime = searchWord.getLastUpdateTime();}if (newKeywords.containsKey(searchWord.getKeyword())) {newKeywords.remove(searchWord.getKeyword());}newKeywords.put(searchWord.getKeyword(), searchWord);}lastUpdateTime = maxNewUpdatedTime;currentKeywords = newKeywords;}private List<SearchWord> getSearchWords(long lastUpdateTime) {// TODO: 从数据库中取出更新时间>lastUpdateTime的数据return null;}

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

相关文章:

  • D. Jumping on Walls bfs
  • preg_replace调用system(“ls“)
  • MT8788核心板主要参数介绍_联发科MTK安卓核心板智能模块
  • Matlab批量提取图片特征向量
  • 数据库系统原理与实践 笔记 #8
  • Ubuntu 和 Windows 文件互传
  • 如何在WPF应用程序中全局捕获异常
  • 自定义Matplotlib中的颜色映射(cmap)
  • Ansible的filter
  • Qt绘制各种图表
  • 【科研新手指南4】ChatGPT的prompt技巧 心得
  • 龙蜥社区联合浪潮信息发布《eBPF技术实践白皮书》(附下载链接)
  • 屏幕截图软件 Snagit mac中文版软件特点
  • 四、Ribbon负载均衡
  • 【Git】第二篇:基本操作(创建本地仓库)
  • vuex——重置vuex数据
  • WebSphere Liberty 8.5.5.9 (三)
  • 如何区分一个项目是react还react native
  • 网易有道开源语音合成引擎“易魔声”
  • [量子计算与量子信息] 2.1 线性代数
  • 【PG】PostgreSQL 目录结构
  • H5游戏源码分享-超级染色体小游戏
  • NOIP 2017 宝藏----Java题解
  • 数据结构和算法的重要性
  • 2023.11.10 信息学日志
  • 0基础学习VR全景平台篇第120篇:极坐标处理接缝 - PS教程
  • Python---综合案例:通讯录管理系统---涉及点:列表、字典、死循环
  • Vite探索:构建、启程、原理、CSS艺术与插件魔法
  • 网工内推 | 网工校招,金融、软件行业,HCIE认证优先,最高15薪
  • CVE-2023-25194 Kafka JNDI 注入分析