克隆是指克隆對象,在堆空間複製一塊內存,是完全的兩個對象,不是指針指向!淺克隆是指克隆一個對象,而該對象的屬性只是基本數據類型,只克隆出該對象!深度克隆是指克隆的目標裏面還有引用類型,引用類型裏還有引用類型,同時把引用類型克隆出來叫深度克隆!常用的方法有兩種,第一,需克隆的對象實現cloneable接口;第二,使用commons包提供的克隆方法。這兩種方法都能實現深度克隆!
原型模式-Prototype(淺度克隆)
-
public class AbstractSpoon implements Cloneable
{
String spoonName;
public void setSpoonName(String spoonName) {this.spoonName = spoonName;}
public String getSpoonName() {return this.spoonName;}
public Object clone() //重寫父類object clone方法,把修飾限制符號提升爲public
{
Object object = null;
try {
object = super.clone();
} catch (CloneNotSupportedException exception) {
System.err.println("AbstractSpoon is not Cloneable");
}
return object;
}
}
- 原型模式-Prototype(深度克隆)
- public Man deepClone(){
try{
- ByteArrayOutputStream bo = new ByteArrayOutputStream();
- ObjectOutputStream outObj = new ObjectOutputStream(bo);
- outObj.writeObject(this);
- ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
- ObjectInputStream outIn = new ObjectInputStream(bi);
- Man m = (Man)outIn.readObject();
- return m;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }