当前位置:   article > 正文

原型模式 深拷贝_原型深拷贝

原型深拷贝

浅拷贝见博客原型模式 浅拷贝
发送邮件,邮件中有附件,深拷贝实现了附件也拷贝了一份。在附件中再加入了一个对象,序列化后也复制了,实验证明深拷贝会将引用对象的引用对象也都复制

public class Test {
    public static void main(String[] args) {
        Email email = new Email(new Attachment());
        Email copyEmail =(Email) email.deepClone();
        System.out.println(email == copyEmail);
        System.out.println(email.equals(copyEmail));
        System.out.println(email.getAttachment() == copyEmail.getAttachment());
        System.out.println(email.getAttachment().equals(copyEmail.getAttachment()));
        System.out.println(email.getAttachment().getCat() == copyEmail.getAttachment().getCat());
    }
}

class Attachment implements Serializable{
    private Cat cat = new Cat();
    public void download(){
        System.out.println("下载附件");
    }

    public Cat getCat() {
        return cat;
    }
}

class Email implements Serializable{
    private Attachment attachment;

    public Email(Attachment attachment) {
        this.attachment = attachment;
    }


    public Object deepClone(){
        try {
            //将对象写入流中
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            oos.close();
            //将对象从流中取出
            InputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
            Object o = ois.readObject();
            ois.close();
            return o;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Attachment getAttachment() {
        return attachment;
    }

    public void display(){
        System.out.println("查看邮件");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

//Email类没有重写equals方法,所以这里equals和==是一样的,如果是String重写了equals方法的话会返回true的。
输出:false
false
false
false
false

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/68506
推荐阅读
相关标签
  

闽ICP备14008679号