栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

设计模式之原型模式

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

设计模式之原型模式

package 原型模式;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Demo {
    //保持老数据
    private HashMap currentKeywords=new HashMap<>();


    private long lastUpdateTime = -1;

    public void refresh() {
        currentKeywords.put("1","wuuw");
        currentKeywords.put("2","wuuw");
        currentKeywords.put("3","wuuw");
        // 浅拷贝
        HashMap newKeywords = (HashMap) currentKeywords.clone();

        // 从数据库中取出更新时间>lastUpdateTime的数据,放入到newKeywords中
        List toBeUpdatedSearchWords = new ArrayList<>();
        toBeUpdatedSearchWords.add("1");
        toBeUpdatedSearchWords.add("2");

        int i = 0;
        if(newKeywords.size() <= toBeUpdatedSearchWords.size()){
            i = toBeUpdatedSearchWords.size();
        }
        if(toBeUpdatedSearchWords.size() <= newKeywords.size()){
            i = newKeywords.size();
        }

        long maxNewUpdatedTime = lastUpdateTime;
        for (int j= 0; j<= i; j++ ) {
            String searchWord = "";
            if (j< toBeUpdatedSearchWords.size()){
                searchWord = toBeUpdatedSearchWords.get(j);
            }
            if (newKeywords.containsKey(searchWord)) {
            newKeywords.remove(newKeywords);
            }else {
                newKeywords.remove(newKeywords);
            }

            newKeywords.put(searchWord, searchWord);

        lastUpdateTime = maxNewUpdatedTime;
        currentKeywords = newKeywords;
    }

    public static void main(String[] args) {
        Demo demo = new Demo();
        demo.refresh();
        demo.currentKeywords.forEach((key,value) ->{
            System.out.println("Key = " + key + "  " + " Value = " + value);
        });
    }
}

  1. 如果对象的创建成本比较大, 而同一个类的不同对象之间差别不大(大部分字段都相同) , 在这种情况下,
    我们可以利用对已有对象(原型)进行复制 (或者叫拷贝) 的方式来创建新 对象, 以达到节省创建时间的目的。
    这种基于原型来创建对象的方式就叫作 原型设计模式 ( Prototype Design Pattern) , 简称 原型模式
    java中clone就是原型模式
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/963242.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号