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

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

AccountManager 負責管理與產生 Account,並提供副本;Account 是 ConcretePrototype;Client 是呼叫方;Cloneable 對應 Prototype。
典型的 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; }
}
以單例形式管理帳號,並依需求回傳「原始物件」或「複製品」:
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);
}
}
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();
}
}
}

淺拷貝是把物件的所有欄位做一次值複製。上面的 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,原始物件也會一起被改掉。因此這裡必須改用深拷貝。
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 則負責管理。

Android Studio NDK 基礎使用教程
NDK 是什麼?Android 平台基於 Java 實現、運行於虛擬機之上,因此使用 SDK 開發需要用 Java 編寫。但並不僅限於 Java——Google 在 An
Android 與 JavaScript 跨平台異步互動實作
在混合式 App 或 WebView 頁面中,常會遇到 Android 原生程式與網頁 JavaScript 需要互相呼叫的情境。若接口存在跨來源限制,也能透過 WebV
Android 為應用添加選單的完整實作方法
為應用添加選單是 Android 開發中的常見需求。添加選單的方法有很多種,但最推薦的方式是用 XML 來創建選單,這樣結構清晰、易於維護。本文就來完整示範整個流程。 建
Android 動畫機制與技巧(五)——Android 5.X 的 SVG 向量動畫
Google 在 Android 5.X 中加入了對 SVG 向量圖形的支援,這對打造高效能的動畫意義重大。先來釐清 SVG 的概念。 可縮放向量圖形(Scalable