Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 原型模式詳解:淺拷貝與深拷貝的實戰比較

編輯:關於 Android 程式設計

原型模式屬於創建型設計模式,主要用於建立昂貴或耗時的物件。它透過複製既有物件來產生新物件,藉此節省時間與記憶體。

模式結構

  • Client:客戶端,呼叫複製方法的類別
  • Prototype:宣告 clone() 等方法的抽象原型介面
  • ConcretePrototype:具體的原型實作

案例:多帳號系統管理

我們要做一個類似多使用者登入的簡單系統。使用者只能在「我的」頁面建立帳號並修改屬性,其他頁面只能讀取、不能修改。但隨著版本迭代,難保有人在其他地方動了使用者資料,造成全域性的問題。因此與其共用同一個物件,不如在需要的地方使用它的副本——這正是原型模式的用武之地。

package 結構如下:

AccountManager 負責管理與產生 Account,並提供副本;Account 是 ConcretePrototype;Client 是呼叫方;Cloneable 對應 Prototype。

Account 類別

典型的 model 類別,實作 Cloneable:

public class Account implements Cloneable {
    private int id;
    private String name;
    private int age;
    private String desc;

    public Account(int id, int age, String name, String desc) {
        this.id = id;
        this.age = age;
        this.name = name;
        this.desc = desc;
    }

    public Account clone() {
        Account clone = null;
        try {
            clone = (Account) super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }

    public int getId() { return id; }
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getDesc() { return desc; }
}

AccountManager 類別

以單例形式管理帳號,並依需求回傳「原始物件」或「複製品」:

public class AccountManager {
    public static AccountManager sAccountManager;
    private Map<Integer, Account> accountMap = new HashMap<Integer, Account>();

    private AccountManager() {}

    public static AccountManager getAccountManager() {
        if (sAccountManager == null) {
            synchronized (AccountManager.class) {
                if (sAccountManager == null) {
                    sAccountManager = new AccountManager();
                }
            }
        }
        return sAccountManager;
    }

    public synchronized Account newAccount(int id, int age, String name, String desc) {
        Account account = accountMap.containsKey(id)
                ? accountMap.get(id) : new Account(id, age, name, desc);
        accountMap.put(id, account);
        return account;
    }

    /** 取得副本 */
    public Account getAccountById(int id) throws Exception {
        if (!accountMap.containsKey(id)) {
            throw new Exception("沒有當前 id 的帳號");
        }
        return (Account) accountMap.get(id).clone();
    }

    /** 取得原始物件 */
    public Account getRootAccountById(int id) throws Exception {
        if (!accountMap.containsKey(id)) {
            throw new Exception("沒有當前 id 的帳號");
        }
        return accountMap.get(id);
    }
}

Client 類別

public class Client {
    public static void main(String[] args) {
        // 「我的」頁面:建立新帳號
        AccountManager.getAccountManager().newAccount(1, 13, "Rrtoyewx", "Rrtoyewx 是一個長不大的孩子");

        try {
            Account accountClone = AccountManager.getAccountManager().getAccountById(1);
            Account accountRoot = AccountManager.getAccountManager().getRootAccountById(1);

            System.out.println("age:" + accountClone.getAge());
            System.out.println("id:" + accountClone.getId());
            System.out.println("name:" + accountClone.getName());
            System.out.println("desc:" + accountClone.getDesc());
            System.out.println("accountClone==accountRoot 是: " + (accountClone == accountRoot));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

原型模式的注意事項

  • 必須有提供克隆能力的主體,否則無法 clone。
  • clone 產生的副本不會走建構子。
  • clone 的效率通常優於透過建構子反覆建立物件,因此在需要多次產生結構複雜的物件時,值得考慮原型模式。
  • 必須清楚區分淺拷貝與深拷貝。

淺拷貝與深拷貝

淺拷貝是把物件的所有欄位做一次值複製。上面的 Account 只有八種基本包裝類與 String,屬於典型的淺拷貝,這樣已經足夠。

但如果 Account 多了一個自訂的引用型別欄位 Address,情況就不同了:

public class Account implements Cloneable {
    private int id;
    private String name;
    private int age;
    private String desc;
    private Address address;

    public Account(int id, int age, String name, String desc, Address address) {
        this.id = id;
        this.age = age;
        this.name = name;
        this.desc = desc;
        this.address = address;
    }

    public Address getAddress() { return address; }

    public Account clone() {
        Account clone = null;
        try {
            clone = (Account) super.clone();
            clone.address = this.address.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}
public class Address implements Cloneable {
    private String name;
    private String location;

    public Address() {}
    public Address(String name, String location) {
        this.name = name;
        this.location = location;
    }
}

如果這裡仍採用淺拷貝,執行後印出的 log 會像這樣:

可以清楚看到,new 出來的 Account 與 Clone 出來的 Account 指向的是同一個 Address 物件。這代表保護並不完整——一旦修改副本的 Address,原始物件也會一起被改掉。因此這裡必須改用深拷貝。

深拷貝做法一:讓 Address 也實作 clone()

public Address clone() {
    Address clone = null;
    try {
        clone = (Address) super.clone();
        clone.location = this.location;
        clone.name = this.name;
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    return clone;
}

Account 的 clone() 中呼叫 address.clone():

public Account clone() {
    Account clone = null;
    try {
        clone = (Account) super.clone();
        clone.address = this.address.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
    return clone;
}

深拷貝做法二:序列化

利用物件串流寫入再讀出,也能完成複製:

public Address deepClone() throws IOException, ClassNotFoundException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(this);

    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    return (Address) ois.readObject();
}
public Account clone() {
    Account clone = null;
    try {
        clone = (Account) super.clone();
        clone.address = this.address.deepClone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return clone;
}

兩種做法的輸出結果一致,副本與原始物件此時已指向不同的 Address:

更好的封裝方式

既然原型模式同時存在淺拷貝與深拷貝,model 層的類別就不該只有一個含糊的 clone()。實務上可以自訂一個 PrototypeAble 介面把兩者明確區分開來:

public interface PrototypeAble extends Cloneable, Serializable {
    PrototypeAble lightClone() throws CloneNotSupportedException;
    PrototypeAble deepClone() throws CloneNotSupportedException, ClassNotFoundException, IOException;
    PrototypeAble root();
}

AccountPrototype 類別:

public class AccountPrototype implements PrototypeAble {
    private int id;
    private String name;
    private int age;
    private String desc;
    private Address address;

    public AccountPrototype(int id, int age, String name, String desc, Address address) {
        this.id = id;
        this.age = age;
        this.name = name;
        this.desc = desc;
        this.address = address;
    }

    @Override
    public PrototypeAble lightClone() throws CloneNotSupportedException {
        return (PrototypeAble) super.clone();
    }

    @Override
    public PrototypeAble deepClone() throws CloneNotSupportedException, IOException, ClassNotFoundException {
        AccountPrototype clone = (AccountPrototype) super.clone();
        clone.address = this.address.deepClone();
        return clone;
    }

    @Override
    public PrototypeAble root() { return this; }

    @Override
    public String toString() {
        return "AccountPrototype [id=" + id + ", name=" + name + ", age=" + age
                + ", desc=" + desc + ", address=" + address + "]";
    }
}

AccountManager 類別:

public class AccountManager {
    public static AccountManager sAccountManager;
    private Map<Integer, AccountPrototype> accountMap = new HashMap<Integer, AccountPrototype>();

    private AccountManager() {}

    public static AccountManager getAccountManager() {
        if (sAccountManager == null) {
            synchronized (AccountManager.class) {
                if (sAccountManager == null) {
                    sAccountManager = new AccountManager();
                }
            }
        }
        return sAccountManager;
    }

    public synchronized AccountPrototype newAccount(int id, int age, String name, String desc, Address address) {
        AccountPrototype account = accountMap.containsKey(id)
                ? accountMap.get(id) : new AccountPrototype(id, age, name, desc, address);
        accountMap.put(id, account);
        return account;
    }

    public AccountPrototype getDeepCloneAccountById(int id) throws Exception {
        if (!accountMap.containsKey(id)) throw new Exception("沒有當前 id 的帳號");
        return (AccountPrototype) accountMap.get(id).deepClone();
    }

    public AccountPrototype getLightCloneAccountById(int id) throws Exception {
        if (!accountMap.containsKey(id)) throw new Exception("沒有當前 id 的帳號");
        return (AccountPrototype) accountMap.get(id).lightClone();
    }

    public AccountPrototype getRootAccountById(int id) throws Exception {
        if (!accountMap.containsKey(id)) throw new Exception("沒有當前 id 的帳號");
        return (AccountPrototype) accountMap.get(id).root();
    }
}

Client 類別:

public class Client {
    public static void main(String[] args) {
        AccountManager.getAccountManager().newAccount(1, 13, "Rrtoyewx", "Rrtoyewx 是一個長不大的孩子", new Address("北京", "昌平"));

        try {
            AccountPrototype deepCloneAccount = AccountManager.getAccountManager().getDeepCloneAccountById(1);
            AccountPrototype lightCloneAccount = AccountManager.getAccountManager().getLightCloneAccountById(1);
            AccountPrototype rootAccount = AccountManager.getAccountManager().getRootAccountById(1);

            System.out.println("deepCloneAccount: " + deepCloneAccount);
            System.out.println("lightCloneAccount: " + lightCloneAccount);
            System.out.println("rootAccount: " + rootAccount);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

此時類別結構就與一開始的 UML 圖完全對應:Client 為呼叫方,PrototypeAble 為抽象原型介面,AccountPrototype 與 AddressPrototype 為具體原型,AccountManager 則負責管理。

總結

  1. 原型模式是一種創建型模式。
  2. 適用於構建較複雜、耗時較長的物件。
  3. 複製過程不經過建構方法。
  4. 使用時務必釐清淺拷貝與深拷貝的差異。
  5. 對象簡單時,不建議使用原型模式。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved