用於建立重複的物件,同時又能保證效能。通俗的講,原型模式就是克隆物件,直接copy位元組碼,不走構造方法,效能非常高。ORM中經常用到。
注意
只支援9種資料型別的深拷貝: 8大基本型別(int long float double boolean char short byte )
+String
其他(List等)資料型別預設都是淺拷貝,但是我們也能通過他們自身的clone方法來深拷貝。
List list = new ArrayList();
List cloneList = (List) ((ArrayList) list).clone();
複製程式碼
Prototype.java
實現Cloneable介面,並且重寫clone()方法。
public class Prototype implements Cloneable{
@Override protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}複製程式碼
注:如果不實現該介面而直接呼叫clone()方法會丟擲CloneNotSupportedException異常
PeoplePrototype.java
人原型,用來做被拷貝的物件。
public class PeoplePrototype extends Prototype{
private int age;
private String name;
public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
}
}複製程式碼
Main.java
public class Main {
public static void main(String[] args) {
PeoplePrototype prototype = new PeoplePrototype();
prototype.setAge(20);
prototype.setName("FantJ");
try {
PeoplePrototype clone = (PeoplePrototype)prototype.clone();
System.out.println(clone.getAge());
System.out.println(clone == prototype);
System.out.println(clone+" "+prototype);
System.out.println(clone.getClass() +" "+ prototype.getClass());
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}複製程式碼
控制檯列印:
20falsecom.fantj.prototype.ConcretePrototype@6d6f6e28 com.fantj.prototype.ConcretePrototype@135fbaa4class com.fantj.prototype.ConcretePrototype class com.fantj.prototype.ConcretePrototype複製程式碼