用原型實例指定建立對象的種類,而且經過拷貝這些原型建立新的對象。簡單地理解,其實就是當須要建立一個指定的對象時,咱們恰好有一個這樣的對象,可是又不能直接使用,我會clone一個一毛同樣的新對象來使用;java
public interface IClonePrototype {
IClonePrototype copy();
}
public class ShallowPrototype implements IClonePrototype, Cloneable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public IClonePrototype copy() {
ShallowPrototype shallowPrototype = new ShallowPrototype();
shallowPrototype.setName(this.getName());
return shallowPrototype;
}
/** * Object 裏面的克隆方法 * @throws CloneNotSupportedException 異常 */
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
// 測試
public static void main(String[] args) throws CloneNotSupportedException {
ShallowPrototype shallowPrototype1 = new ShallowPrototype();
shallowPrototype1.setName("LiDaShuang");
ShallowPrototype shallowPrototype2 = (ShallowPrototype) shallowPrototype1.copy();
System.out.println(shallowPrototype1);
System.out.println(shallowPrototype2);
// 獲得實例的內存地址不一樣可是裏面值的內存地址相同
System.out.println(shallowPrototype2.getName() == shallowPrototype1.getName()); // true 內存地址相同
}
複製代碼
public interface IClonePrototype {
IClonePrototype copy();
}
public class DeepPrototype implements IClonePrototype, Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public IClonePrototype copy() {
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return (DeepPrototype) ois.readObject();
}catch (Exception e){
e.printStackTrace();
return null;
}
}
}
// 測試
public static void main(String[] args) throws CloneNotSupportedException {
DeepPrototype deepPrototype1 = new DeepPrototype();
deepPrototype1.setName("LiDaShuang");
DeepPrototype deepPrototype2 = (DeepPrototype) deepPrototype1.copy();
System.out.println(deepPrototype1);
System.out.println(deepPrototype2);
System.out.println(deepPrototype1.getName() == deepPrototype2.getName()); // false 內存地址不相同
}
複製代碼
原型模式的本質就是clone,能夠解決構建複雜對象的資源消耗問題,能再某些場景中提高構建對象的效率;還有一個重要的用途就是保護性拷貝,能夠經過返回一個拷貝對象的形式,實現只讀的限制。ide