目錄
1.簡介
用原型實例指定創建對象的種類,並且通過拷貝這些這些原型創建新的對象。其核心在於clone方法,通過該方法可以進行對象的拷貝。且於final關鍵字衝突。
2.優點
由於clone方法是在內存二進制流的拷貝,相比直接new出來性能更高,尤其是需要在循環體內產生大量對象時非常適用。
3.缺點
由於是在內存中拷貝,所以構造函數是不會被執行的。
4.形式
一般形式,只涉及到對象或者原始類型,如int,char等
public class Prototype implements Cloneable {
@Override
public Prototype clone() {
Prototype prototype = null;
try{
prototype = (Prototype) super.clone();
}catch(CloneNotSupportedException e) {
e.printStackTrace();
System.out.println("異常處理");
}
}
}
淺拷貝,由於Object類提供的clone方法只是拷貝本對象,而對其對象內部的數組,引用對象不會被拷貝,還是指向原生對象內部的元素地址。這樣造成的結果就是可能拷貝過來的對象將會共享私有變量。
public class Prototype implements Cloneable {
private ArrayList<String> arrayList = new ArrayList<String>();
@Override
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype)super.clone();
}catch(CloneNotSupportedException e) {
e.printStackTrace();
System.out.println("異常處理");
}
return prototype;
}
}
深拷貝相比淺拷貝的區別就在於,它同時會拷貝對象內部的數組和引用對象,這樣兩個對象之間將相互不會產生影響。
public class Prototype implements Cloneable {
private ArrayList<String> arrayList = new ArrayList<String>();
@Override
public Prototype clone() {
Prototype prototype = null;
try {
prototype = (Prototype)super.clone();
prototype.arrayList = (ArrayList<String>)this.arrayList.clone();
}catch(CloneNotSupportedException e) {
e.printStackTrace();
System.out.println("異常處理");
}
return prototype;
}
}