Posted on 2007-05-29 15:43
zht 閱讀(959)
評論(0) 編輯 收藏 所屬分類:
設計模式
復制產生對象實例:
使用Prototype模式可以理解為 創造出一個和已有對象一樣的對象
ex)指著面包店櫥窗里的面包告訴老板 我就要這個 雖然不知道名字 也不知道做法 但是能買到和所指的相同的東西。
實例:
1、定義一個接口 實現Cloneable
public interface Product extends Cloneable {
public abstract void use(String s);
public abstract Product createClone();
}
2、聲明一個manage類來根據Product的createClone來進行復制
public class Manager {
private Hashtable showcase = new Hashtable();
public void register(String name, Product proto) {
showcase.put(name, proto);
}
public Product create(String protoname) {
Product p = (Product)showcase.get(protoname);
return p.createClone();
}
}
3、Product類的一個具體實現
public class UnderlinePen implements Product {
private char ulchar;
public UnderlinePen(char ulchar) {
this.ulchar = ulchar;
}
public void use(String s) {
int length = s.getBytes().length;
System.out.println("\"" + s + "\"");
System.out.print(" ");
for (int i = 0; i < length; i++) {
System.out.print(ulchar);
}
System.out.println("");
}
public Product createClone() {
Product p = null;
try {
p = (Product)clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return p;
}
}
4、具體使用
// 預備階段
Manager manager = new Manager();
UnderlinePen upen = new UnderlinePen('~');
MessageBox mbox = new MessageBox('*');
MessageBox sbox = new MessageBox('/');
manager.register("strong message", upen);
manager.register("warning box", mbox);
manager.register("slash box", sbox);
// 實現產生
Product p1 = manager.create("strong message");
p1.use("Hello, world.");
Product p2 = manager.create("warning box");
p2.use("Hello, world.");
Product p3 = manager.create("slash box");
p3.use("Hello, world.");
}
也可以將product聲明成抽象類實現Cloneable接口
并且實現createClone方法
這樣子類中就不用再聲明creatClone方法了 簡化了代碼
clone方法在Object中定義 因此所有類都會繼承clone()方法
Cloneable這個接口表示 可用clone()方法進行復制
clone()方法做的是淺拷貝 所做的操作是直接復制字段內容 并不管該字段對應的對象實例內容 假定有一個數組 當使用clone方法進行拷貝以后 復制的結果,只是對應到該數組的參照 即指向該數組的內存地址 如果想做深拷貝 必須重寫clone方法 記得要加上super.clone()