设计模式学习笔记:原型模式以及深浅拷贝的区别

2022-12-19 0 464

蓝本商业模式也是建立第一类的一类形式,它通常用在这种的情景:控制系统中存有大批完全相同或相近第一类的建立难题,假如用现代的缺省来建立第一类,会十分繁杂所以耗费天然资源。那个这时候采用蓝本商业模式的布季夫形式,能节约许多天数。比如说Java 类中提供更多的Object clone()是蓝本商业模式的应用领域。

一、蓝本商业模式如是说#

蓝本设计商业模式(Prototype Design Pattern)指用两个早已建立的示例做为蓝本,透过拷贝该蓝本第一类来建立两个和蓝本完全相同或相近的新第一类。在Java词汇中就存有布季夫的形式,比如说浅复本和深复本。

对通常的第一类建立,这类不能耗费太少的天然资源,但对负责管理的第一类,比如说第一类的统计数据须要历经繁杂的次序就能获得(比如说次序、次序基元值),总之是须要从 RPC、互联网、资料库、磁盘等十分短距离的IO中加载,那个这时候就能借助蓝本商业模式从其它第一类间接复本,进而增加天然资源的耗用。

二、蓝本商业模式的同时实现#

在Java中蓝本商业模式的同时实现形式是深复本和浅复本,上面来聊聊深复本和浅复本的差别

2.1 深复本和浅复本#

2.1.1 浅复本#

浅复本(Shadow Clone)是把蓝本第一类中的核心成员表达式为值类别的特性都拷贝给布季夫第一类,将为提及类的提及门牌号拷贝给布季夫第一类:

设计模式学习笔记:原型模式以及深浅拷贝的区别

同时实现标识符如下表所示:

//同时实现CloneableUSB 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() throwsCloneNotSupportedException{ 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)是将蓝本第一类中的所有第一类,无论值类别还是提及类别,都拷贝一份给复本第一类:

设计模式学习笔记:原型模式以及深浅拷贝的区别

那么深复本该如何同时实现?所以前面我们发现,在复本时为何须要重写 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 {@codex}, 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 {@codetrue}, but these are not absolute requirements. * While it is typically the case that: * <blockquote> * <pre> * x.clone().equals(x)</pre></blockquote> * will be {@codetrue}, this is not an absolute requirement. * <p> * By convention, the returned object should be obtained by calling * {@codesuper.clone}. If a class and all of its superclasses (except * {@codeObject}) obey this convention, it will be the case that * {@codex.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 {@codesuper.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 {@codesuper.clone} * need to be modified. * <p> * The method {@codeclone} for class {@codeObject} performs a * specific cloning operation. First, if the class of this object does * not implement the interface {@code Cloneable}, then a * {@codeCloneNotSupportedException} is thrown. Note that all arrays * are considered to implement the interface {@codeCloneable} and that * the return type of the {@code clone} method of an array type {@codeT[]} * is {@codeT[]} 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 {@codeObject} does not itself implement the interface * {@code Cloneable}, so calling the {@codeclone} method on an object * whose class is {@codeObject} will result in throwing an * exception at run time. * *@return a clone of this instance. * @throwsCloneNotSupportedException if the objects class does not * support the {@codeCloneable} interface. Subclasses * that override the {@codeclone} method can also * throw this exception to indicate that an instance cannot * be cloned. *@see java.lang.Cloneable */ protected native Object clone() throws CloneNotSupportedException;

从注释能知道,对所有的第一类来说:

x.clone()!=x应当返回 true,因为布季夫第一类不能和原第一类是同两个第一类x.clone().getClass()==x.getClass()应当返回 true,因为布季夫第一类和原第一类的类别是完全相同的x.clone().equals(x)应当返回true,因为采用equals方法比较时,其值都是完全相同的

Java 同时实现复本主要有两个步骤:一是同时实现 Cloneable空USB,二是重写Object的Clone方法后再调用父类的布季夫方法super.clone(),那为何这种做?

复本功能不是两个常用的功能,因此在第一类须要时同时实现即可,这种比较合理,所以在Java词汇中两个类也能同时实现多个USB。对调用clone方法,因为该方法语义的特殊性,所以要有JVM的间接支持,而clone方法是那个调用USB,一旦有类调用那个方法,就能同时实现复本功能了。

2.1.3 深复本的同时实现形式#

深复本的同时实现形式有很多种,大体上有这种几种:

1.所有第一类都同时实现深复本#

这种形式须要让类中所有提及第一类都同时实现复本,进而同时实现类的深复本,标识符如下表所示:

public class CloneExample { public static void main(String[] args) throwsCloneNotSupportedException{ // 建立被赋值第一类 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; privateString 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 方法 * @throwsCloneNotSupportedException */ @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; privateString 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 方法 * @throwsCloneNotSupportedException */ @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 = newPeople(people1.getId(), people1.getName(),newAddress(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; } publicAddressgetAddress() { 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 = newObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(obj); objectOutputStream.close();//分配内存,写入原始第一类并生成新第一类 ByteArrayInputStream byteArrayInputStream = newByteArrayInputStream(byteArrayOutputStream.toByteArray()); ObjectInputStream objectInputStream =newObjectInputStream(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; publicIntegergetId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { returnname; }public void setName(String name) { this.name = name; } public Address getAddress() { returnaddress; }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; } } }

在借助字节流进行复本时,要注意每个第一类必须同时实现 SerizlizableUSB,标识自己能被序列化,否则就会抛出(

java.io.NotSerizlizableException)异常。

4.透过Apache Commons Lang同时实现深复本#

相对方法3,那个方法能间接调用,同时实现标识符如下表所示:

People people2 = (People)SerizlizationUtils.clone(people1); //其它部分和方法3完全相同,省略

5.透过JSON工具类同时实现深复本#

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

在该方法中,不须要对People和Address类进行标识序列化。采用JSON 工具类会先把第一类转化成字符串,然后再从字符串转化成新的第一类,因此不能和蓝本第一类有关联。进而同时实现了深度复本,其它类似的 JSON 工具类的同时实现形式也是如此。

三、总结#

蓝本商业模式在 Java 中主要有两种同时实现形式:深复本和浅复本,两者差别是深复本会拷贝提及第一类,浅复本只会拷贝提及第一类的门牌号。深复本相对浅复本更加耗时和天然资源。

为何有深复本的存有呢?因为对可变第一类来说,浅复本对提及第一类的门牌号复本会带来修改风险。所以在可变第一类的情景下,尽量还是选择深复本的形式进行拷贝。

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务