当前位置:首页 > 经验 >

深拷贝和浅拷贝和零拷贝的区别(深拷贝与浅拷贝示意图)

来源:原点资讯(www.yd166.com)时间:2022-10-24 22:15:15作者:YD166手机阅读>>

原型模式也是创建对象的一种方式,它一般用在这样的场景:系统中存在大量相同或相似对象的创建问题,如果用传统的构造函数来创建对象,会比较复杂而且耗费资源。这个时候使用原型模式的克隆方式,能够节省不少时间。比如Java 类中提供的Object clone()就是原型模式的应用。

一、原型模式介绍#

原型设计模式(Prototype Design Pattern)指用一个已经创建的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。在Java语言中就存在克隆的方式,比如浅拷贝和深拷贝。

对于一般的对象创建,本身不会花费太多的资源,但是对于负责的对象,比如对象的数据需要经过复杂的计算才能得到(比如排序、计算哈希值),抑或是需要从 RPC、网络、数据库、文件系统等非常慢速的IO中读取,这个时候就可以利用原型模式从其他对象直接拷贝,从而减少资源的消耗。

二、原型模式的实现#

在Java中原型模式的实现方式就是深拷贝和浅拷贝,下面来谈谈深拷贝和浅拷贝的区别

2.1 深拷贝和浅拷贝#2.1.1 浅拷贝#

浅拷贝(Shadow Clone)是把原型对象中的成员变量为值类型的属性都复制给克隆对象,将为引用类的引用地址复制给克隆对象:

深拷贝和浅拷贝和零拷贝的区别,深拷贝与浅拷贝示意图(1)

实现代码如下:

//实现Cloneable接口 public class Shadowcopy implements Cloneable{ private String name; private int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public ShadowCopy(String name, int id) { this.name = name; this.id = id; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } //调用测试 public class PrototypeTest { public static void main(String[] args) throws CloneNotSupportedException { ShadowCopy shadowCopy = new ShadowCopy("ethan", 01); ShadowCopy copy = (ShadowCopy) shadowCopy.clone(); System.out.println("name:" copy.getName() " " "id:" copy.getId()); System.out.println(copy == shadowCopy); } }

最后的测试结果copy == shadowCopy显示为false,说明为浅拷贝。我们再看看深拷贝:

2.1.2 深拷贝#

深拷贝(Deep Clone)是将原型对象中的所有对象,无论值类型还是引用类型,都复制一份给拷贝对象:

深拷贝和浅拷贝和零拷贝的区别,深拷贝与浅拷贝示意图(2)

那么深拷贝该如何实现?而且前面我们发现,在拷贝时为何需要重写 Object的 clone方法?先来看看其源码,发现clone方法是一个本地方法:

/** * Creates and returns a copy of this object. The precise meaning * of "copy" may depend on the class of the object. The general * intent is that, for any object {@code x}, the expression: * <blockquote> * <pre> * x.clone() != x</pre></blockquote> * will be true, and that the expression: * <blockquote> * <pre> * x.clone().getClass() == x.getClass()</pre></blockquote> * will be {@code true}, but these are not absolute requirements. * While it is typically the case that: * <blockquote> * <pre> * x.clone().equals(x)</pre></blockquote> * will be {@code true}, this is not an absolute requirement. * <p> * By convention, the returned object should be obtained by calling * {@code super.clone}. If a class and all of its superclasses (except * {@code Object}) obey this convention, it will be the case that * {@code x.clone().getClass() == x.getClass()}. * <p> * By convention, the object returned by this method should be independent * of this object (which is being cloned). To achieve this independence, * it may be necessary to modify one or more fields of the object returned * by {@code super.clone} before returning it. Typically, this means * copying any mutable objects that comprise the internal "deep structure" * of the object being cloned and replacing the references to these * objects with references to the copies. If a class contains only * primitive fields or references to immutable objects, then it is usually * the case that no fields in the object returned by {@code super.clone} * need to be modified. * <p> * The method {@code clone} for class {@code Object} performs a * specific cloning operation. First, if the class of this object does * not implement the interface {@code Cloneable}, then a * {@code CloneNotSupportedException} is thrown. Note that all arrays * are considered to implement the interface {@code Cloneable} and that * the return type of the {@code clone} method of an array type {@code T[]} * is {@code T[]} where T is any reference or primitive type. * Otherwise, this method creates a new instance of the class of this * object and initializes all its fields with exactly the contents of * the corresponding fields of this object, as if by assignment; the * contents of the fields are not themselves cloned. Thus, this method * performs a "shallow copy" of this object, not a "deep copy" operation. * <p> * The class {@code Object} does not itself implement the interface * {@code Cloneable}, so calling the {@code clone} method on an object * whose class is {@code Object} will result in throwing an * exception at run time. * * @return a clone of this instance. * @throws CloneNotSupportedException if the object's class does not * support the {@code Cloneable} interface. Subclasses * that override the {@code clone} method can also * throw this exception to indicate that an instance cannot * be cloned. * @see java.lang.Cloneable */ protected native Object clone() throws CloneNotSupportedException;

从注释可以知道,对于所有的对象来说:

  1. x.clone()!=x应当返回 true,因为克隆对象不能和原对象是同一个对象
  2. x.clone().getClass()==x.getClass()应当返回 true,因为克隆对象和原对象的类型是相同的
  3. x.clone().equals(x)应当返回true,因为使用equals方法比较时,其值都是相同的

Java 实现拷贝主要有两个步骤:一是实现 Cloneable空接口,二是重写Object的Clone方法后再调用父类的克隆方法super.clone(),那为何这样做?

拷贝功能不是一个常用的功能,因此在对象需要时实现即可,这样比较合理,而且在Java语言中一个类也可以实现多个接口。对于调用clone方法,因为该方法语义的特殊性,所以要有JVM的直接支持,而clone方法就是这个调用接口,一旦有类调用这个方法,就可以实现拷贝功能了。

2.1.3 深拷贝的实现方式#

深拷贝的实现方式有很多种,大体上有这样几种:

1.所有对象都实现深拷贝#

这种方式需要让类中所有引用对象都实现拷贝,从而实现类的深拷贝,代码如下:

public class CloneExample { public static void main(String[] args) throws CloneNotSupportedException { // 创建被赋值对象 Address address = new Address(110, "北京"); People p1 = new People(1, "Java", address); // 克隆 p1 对象 People p2 = p1.clone(); // 修改原型对象 p1.getAddress().setCity("西安"); // 输出 p1 和 p2 地址信息 System.out.println("p1:" p1.getAddress().getCity() " p2:" p2.getAddress().getCity()); } /** * 用户类 */ static class People implements Cloneable { private Integer id; private String name; private Address address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public People(Integer id, String name, Address address) { this.id = id; this.name = name; this.address = address; } /** * 重写 clone 方法 * @throws CloneNotSupportedException */ @Override protected People clone() throws CloneNotSupportedException { People people = (People) super.clone(); people.setAddress(this.address.clone()); // 引用类型克隆赋值 return people; } } /** * 地址类 */ static class Address implements Cloneable { private Integer id; private String city; public Address(Integer id, String city) { this.id = id; this.city = city; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } /** * 重写 clone 方法 * @throws CloneNotSupportedException */ @Override protected Address clone() throws CloneNotSupportedException { return (Address) super.clone(); } } } 2.通过构造方法实现深拷贝#

如果构造方法的参数为基本数据类型或者字符串类型,直接进行赋值即可,如果是对象类型,则需要重新 new 一个对象,实现代码如下:

public class CloneExample2 { public static void main(String[] args) { Address address = new Address(100, "北京"); People people1 = new People(1, "ethan", address); People people2 = new People(people1.getId(), people1.getName(), new Address(people1.getAddress().getId(), people1.getAddress().getCity())); } static class People { private Integer id; private String name; private Address address; public People(Integer id, String name, Address address) { this.id = id; this.name = name; this.address = address; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } static class Address { private Integer id; private String city; public Address(Integer id, String city) { this.id = id; this.city = city; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } } } 3.通过字节流实现深拷贝#

可以通过 JDK 自带的字节流实现深拷贝的方式,是先将要原型对象写入到内存中的字节流,然后再从这个字节流中读出刚刚存储的信息,来作为一个新的对象返回,那么这个克隆对象和原型对象就不存在任何地址上的共享,实现代码如下:

public class CloneExample3 { public static void main(String[] args) { Address address = new Address(100, "北京"); People people1 = new People(1, "ethan", address); //字节流拷贝对象 People people2 = StreamClone.clone(people1); } static class StreamClone { public static <T extends Serializable> T clone(People obj) { T cloneObj = null; try { //写入字节流 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(obj); objectOutputStream.close(); //分配内存,写入原始对象并生成新对象 ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); //返回生成的新对象 cloneObj = (T) objectInputStream.readObject(); objectInputStream.close(); } catch (Exception e) { e.printStackTrace(); } return cloneObj; } } static class People implements Serializable { private Integer id; private String name; private Address address; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public People(Integer id, String name, Address address) { this.id = id; this.name = name; this.address = address; } } static class Address implements Serializable { private Integer id; private String city; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public Address(Integer id, String city) { this.id = id; this.city = city; } } }

在利用字节流进行拷贝时,要注意每个对象必须实现 Serizlizable接口,标识自己可以被序列化,否则就会抛出(java.io.NotSerizlizableException)异常。

4.通过Apache Commons Lang实现深拷贝#

相对于方法3,这个方法可以直接调用,实现代码如下:

People people2 = (People)SerizlizationUtils.clone(people1); //其他部分和方法3相同,省略 5.通过JSON工具类实现深拷贝#

Gson gson = new Gson(); People people2 = gson.fromJson(gson.toJson(people1), People.class);

在该方法中,不需要对People和Address类进行标识序列化。使用JSON 工具类会先把对象转化成字符串,然后再从字符串转化成新的对象,因此不会和原型对象有关联。从而实现了深度拷贝,其他类似的 JSON 工具类的实现方式也是如此。

三、总结#

原型模式在 Java 中主要有两种实现方式:深拷贝和浅拷贝,两者区别是深拷贝会复制引用对象,浅拷贝只会复制引用对象的地址。深拷贝相对于浅拷贝更加耗时和资源。

为何有深拷贝的存在呢?因为对于可变对象来说,浅拷贝对于引用对象的地址拷贝会带来修改风险。所以在可变对象的场景下,尽量还是选择深拷贝的方式进行复制。

栏目热文

深拷贝和浅拷贝的方法(深拷贝的方法及优缺点)

深拷贝和浅拷贝的方法(深拷贝的方法及优缺点)

由于JavaScript中对象是引用类型,保存的是地址,深、浅拷贝的区别是,当拷贝结束后,在一定程度上改变原对象中的某一...

2022-10-24 22:44:42查看全文 >>

白糖和化肥为什么能爆炸(国家为什么要管控白糖)

白糖和化肥为什么能爆炸(国家为什么要管控白糖)

【军武次位面】作者:leon最近,克里米亚大桥被炸毁的消息想必是引起了全球的关注与报道,作为当前俄乌冲突中的极具战略价值...

2022-10-24 22:10:34查看全文 >>

满月剃头仪式流程(满月剪胎毛口诀)

满月剃头仪式流程(满月剪胎毛口诀)

引言中国人从古至今都特别重视“满月”这个日子,小孩生下来满一个月的时候,家人们就会设席摆宴,邀请朋好友来给孩子庆祝满月。...

2022-10-24 21:59:43查看全文 >>

产妇满月当天禁忌(产妇满月当天吃什么好)

产妇满月当天禁忌(产妇满月当天吃什么好)

满月即是弥月之喜,这是孩子出生后比较重要的民俗喜事之一,人们常说的“满月酒”便是指孩子产后满月时敬警神祀、庆祝请客的酒...

2022-10-24 21:53:38查看全文 >>

剃胎发最佳时间(剃胎头有什么讲究和忌讳)

剃胎发最佳时间(剃胎头有什么讲究和忌讳)

宝宝出生一个月了,不少家庭开始准备一件大事,那就是给宝宝过满月,有的地方还要当着亲戚朋友的面给宝宝剃胎发,不管是男宝宝还...

2022-10-24 22:15:46查看全文 >>

为什么要深拷贝浅拷贝(零拷贝和深拷贝)

为什么要深拷贝浅拷贝(零拷贝和深拷贝)

关于对象的拷贝,大部分时间我们用的都是浅拷贝,比如赋值符号(“=”)以及memcpy()等。那么既然浅拷贝这么简单,为...

2022-10-24 22:08:28查看全文 >>

浅拷贝和深拷贝的值会不会变(高拷贝和低拷贝的区别)

浅拷贝和深拷贝的值会不会变(高拷贝和低拷贝的区别)

前面我们曾经聊到列表从内存的角度是什么样的?有兴趣的可以关注我,看一下《python之从内存读写的角度,学习并玩转lis...

2022-10-24 22:44:50查看全文 >>

深拷贝解决浅拷贝的问题(深拷贝的缺点)

深拷贝解决浅拷贝的问题(深拷贝的缺点)

作者:小丑转发链接:https://mp.weixin.qq.com/s/i_vGi8C5PBa_KOV7MtVPWQ前...

2022-10-24 22:51:29查看全文 >>

深拷贝和浅拷贝的简单理解(深拷贝解决浅拷贝的问题)

深拷贝和浅拷贝的简单理解(深拷贝解决浅拷贝的问题)

前言平时我们从数据库查询出 po 对象,要返回给前端时,会有另一个对象 vo,此时我们需要将 po 的值复制给 vo,如...

2022-10-24 22:07:09查看全文 >>

简述浅拷贝和深拷贝的区别(浅拷贝深拷贝哪个是原地操作)

简述浅拷贝和深拷贝的区别(浅拷贝深拷贝哪个是原地操作)

使用场景:开发的时候对引用类型进行处理,为了避免修改一个引用类型数据时,其他用这个变量来赋值的变量也都被改变了。如下例子...

2022-10-24 22:53:14查看全文 >>

文档排行