1.定義#
用原型實例指定創(chuàng)建對象的種類,并且通過拷貝這些原型創(chuàng)建新的對象。在JAVA中通過繼承Clonealbe接口,并實現(xiàn)其中的clone方法,即可實現(xiàn)原型的拷貝,需要注意的是clone方法拷貝的是二進制流,所以使用clone生成新的對象時不會調(diào)用類的構(gòu)造方法,并且clone是淺拷貝方法,注意是用深拷貝拷貝非基本類型(基本類型為int,char,string等)。另外被定義為final的屬性無法被拷貝。
2.類圖#
十分簡單,此處不貼圖了。
3.實現(xiàn)#
public class Thing implements Cloneable{
private ArrayList<String> arrayList = new ArrayList<String>();
@Override
public Thing clone() {
//通過繼承Cloneable接口,實現(xiàn)clone方法
Thing thing = null;
try {
thing = (Thing) super.clone();
//深拷貝問題解決
thing.arrayList = (ArrayList<String>) this.arrayList.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return thing;
}
public void setValue(String value) {
this.arrayList.add(value);
}
public ArrayList<String> getValue() {
return this.arrayList;
}
}