Prototype 模式 透過複製現有原型物件來建立新物件,而非透過 new 實例化。適用於:
clone() 方法,通常繼承 Cloneable。clone(),執行淺層或深層複製。clone() 取得新實例。package meconsea;
import java.io.Serializable;
public interface IPrototypeRam extends Cloneable, Serializable {
String getName();
void setName(String name);
}
package meconsea;
public class PrototypeRam implements IPrototypeRam {
private String name;
public PrototypeRam() {
this.name = "this is prototype!";
}
@Override
public String getName() { return name; }
@Override
public void setName(String name) { this.name = name; }
@Override
public Object clone() {
try {
return super.clone(); // 淺層複製,String 為不可變故安全
} catch (CloneNotSupportedException e) {
throw new RuntimeException("PrototypeRam not cloneable", e);
}
}
}
package meconsea;
import java.util.HashMap;
public class PrototypeManager {
private static PrototypeManager instance;
private final HashMap registry = new HashMap<>();
private PrototypeManager() {}
public static synchronized PrototypeManager getInstance() {
if (instance == null) instance = new PrototypeManager();
return instance;
}
public void register(String name, Object prototype) {
registry.put(name, prototype);
}
public void unregister(String name) {
registry.remove(name);
}
public Object getPrototype(String name) {
Object proto = registry.get(name);
if (proto == null) {
try {
// 動態載入並自動註冊
proto = Class.forName(name).newInstance();
register(name, proto);
} catch (Exception e) {
throw new RuntimeException("Prototype not found: " + name, e);
}
}
return proto;
}
}
package meconsea;
public class PrototypeClient {
public static void main(String[] args) {
PrototypeManager pm = PrototypeManager.getInstance();
String className = "meconsea.PrototypeRam";
// 取得原型 (首次會自動載入並註冊)
PrototypeRam prototype = (PrototypeRam) pm.getPrototype(className);
System.out.println("原型名稱:" + prototype.getName());
// 複製 10 個實例並修改名稱
for (int i = 0; i < 10; i++) {
PrototypeRam clone = (PrototypeRam) prototype.clone();
clone.setName(clone.getName() + i);
System.out.printf("Clone %d: %s (原型不變: %s)%n", i, clone.getName(), prototype.getName());
}
}
}
clone() 執行深層複製,或改用序列化/建構式複製。Prototype 模式以「複製」取代「建構」,配合原型管理器實現靈活的物件創建機制。掌握淺層/深層複製差異與動態註冊技巧,能有效解決執行期物件類型不確定或初始化成本高的問題。