设计模式之原型模式

package 原型模式;

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

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


    private long lastUpdateTime = -1;

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

        // 从数据库中取出更新时间>lastUpdateTime的数据,放入到newKeywords中
        List<String> 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就是原型模式
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值