zoukankan      html  css  js  c++  java
  • 设计模式第4篇:原型设计模式

    一.原型设计模式要解决的问题

      当创建一个对象需要大量的时间和资源时,这时如果已经存在一个类似的对象,我们就应该考虑原型设计模式。原型设计模式通过拷贝一份已经存在的对象并根据自己的需要来修改该对象,该模式要求复制的对象本身需要有复制特性,它不应该被其他类去复制。java中的原型设计模式通过克隆来实现,具体通过深拷贝实现还是浅拷贝实现需要根据具体需求决定。

    附一个简单的Java代码实例如下:

    class Employments implements Cloneable{
        private List<String> empList;
        public Employments(){
            empList=new ArrayList<String>();
        }
        public Employments(List<String> empList){
            this.empList=empList;
        }
        /*模拟从数据库取数据并放入empList容器*/
        public void loadData(){
            empList.add("zhangsan");
            empList.add("lisi");
            empList.add("wangwu");
        }
        public List<String> getEmpList(){
            return empList;
        }
    /*此处的克隆用的是深拷贝*/ @Override
    public Object clone(){ ArrayList<String> list=new ArrayList<>(); for(String s:this.getEmpList()){ list.add(s); } return new Employments(list); } }

    测试代码如下:

    public class PrototypeTest{
        public static void main(String[] args) {
            Employments employments = new Employments();
            employments.loadData();
            Employments employmentsNew=(Employments)employments.clone();
            List<String> empListNew=employmentsNew.getEmpList();
            empListNew.add("test");
            System.out.println("empList:"+employments.getEmpList());
            System.out.println("empListNew:"+empListNew);
        }
    
    }

    返回结果如下:

    empList:[zhangsan, lisi, wangwu]
    empListNew:[zhangsan, lisi, wangwu, test]
  • 相关阅读:
    [Leetcode]279.完全平方数
    map处理数组 替换item的值
    Immutable数据详解 merge方法及其原理解释
    dev-server的mock配置
    react 国际化 react-i18next
    import * as xxx from 'xxx'
    http-server测试本地打包程序是否有问题
    git 操作
    react hook 官方文档阅读笔记
    吐槽下百度搜索引擎的权重问题
  • 原文地址:https://www.cnblogs.com/quxiangxiangtiange/p/10217422.html
Copyright © 2011-2022 走看看