設計模式學習筆記(六)原型模式以及深淺拷貝的區別

歸斯君發表於2022-03-27

原型模式也是建立物件的一種方式,它一般用在這樣的場景:系統中存在大量相同或相似物件的建立問題,如果用傳統的建構函式來建立物件,會比較複雜而且耗費資源。這個時候使用原型模式的克隆方式,能夠節省不少時間。比如Java 類中提供的Object clone()就是原型模式的應用。

一、原型模式介紹

原型設計模式(Prototype Design Pattern)指用一個已經建立的例項作為原型,通過複製該原型物件來建立一個和原型相同或相似的新物件。在Java語言中就存在克隆的方式,比如淺拷貝和深拷貝。

對於一般的物件建立,本身不會花費太多的資源,但是對於負責的物件,比如物件的資料需要經過複雜的計算才能得到(比如排序、計算雜湊值),抑或是需要從 RPC、網路、資料庫、檔案系統等非常慢速的IO中讀取,這個時候就可以利用原型模式從其他物件直接拷貝,從而減少資源的消耗。

二、原型模式的實現

在Java中原型模式的實現方式就是深拷貝和淺拷貝,下面來談談深拷貝和淺拷貝的區別

2.1 深拷貝和淺拷貝

2.1.1 淺拷貝

淺拷貝(Shadow Clone)是把原型物件中的成員變數為值型別的屬性都複製給克隆物件,將為引用類的引用地址複製給克隆物件:

實現程式碼如下:

//實現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)是將原型物件中的所有物件,無論值型別還是引用型別,都複製一份給拷貝物件:

那麼深拷貝該如何實現?而且前面我們發現,在拷貝時為何需要重寫 Objectclone方法?先來看看其原始碼,發現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空介面,二是重寫ObjectClone方法後再呼叫父類的克隆方法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);

在該方法中,不需要對PeopleAddress類進行標識序列化。使用JSON 工具類會先把物件轉化成字串,然後再從字串轉化成新的物件,因此不會和原型物件有關聯。從而實現了深拷貝,其他類似的 JSON 工具類的實現方式也是如此。

三、總結

原型模式在 Java 中主要有兩種實現方式:深拷貝和淺拷貝,兩者區別是深拷貝會複製引用物件,淺拷貝只會複製引用物件的地址。深拷貝相對於淺拷貝更加耗時和資源。

為何有深拷貝的存在呢?因為對於可變物件來說,淺拷貝對於引用物件的地址拷貝會帶來修改風險。所以在可變物件的場景下,儘量還是選擇深拷貝的方式進行復制。

參考資料

https://time.geekbang.org/column/article/200786

《Java 重學設計模式》

https://kaiwu.lagou.com/course/courseInfo.htm?courseId=59#/detail/pc?id=1767

http://c.biancheng.net/view/1343.html

相關文章