原型模式

2020-05-17  本文已影响0人  俊果果

一、介绍

当我们要复制一个对象时,传统的方法是new一个新的对象,然后依次用已存在对象的每个属性给新对象赋值。这种方式存在的问题是:

二、实现方法

直接贴几篇讲的比较清楚的文章吧

浅拷贝和深拷贝:

浅拷贝

深拷贝

//深拷贝 - 通过对象的序列化实现 (推荐)
    public Object deepClone() {
        
        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        
        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this); //当前这个对象以对象流的方式输出
            
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObj = (DeepProtoType)ois.readObject();
            
            return copyObj;
            
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return null;
        } finally {
            //关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e2) {
                // TODO: handle exception
                System.out.println(e2.getMessage());
            }
        }
    }

三、总结

上一篇 下一篇

猜你喜欢

热点阅读