1.定義#
用原型實(shí)例指定創(chuàng)建對(duì)象的種類(lèi)昆庇,并且通過(guò)拷貝這些原型創(chuàng)建新的對(duì)象。在JAVA中通過(guò)繼承Clonealbe接口整吆,并實(shí)現(xiàn)其中的clone方法拱撵,即可實(shí)現(xiàn)原型的拷貝拴测,需要注意的是clone方法拷貝的是二進(jìn)制流集索,所以使用clone生成新的對(duì)象時(shí)不會(huì)調(diào)用類(lèi)的構(gòu)造方法务荆,并且clone是淺拷貝方法,注意是用深拷貝拷貝非基本類(lèi)型(基本類(lèi)型為int蛹含,char浦箱,string等)。另外被定義為final的屬性無(wú)法被拷貝祠锣。
2.類(lèi)圖#
十分簡(jiǎn)單酷窥,此處不貼圖了。
3.實(shí)現(xiàn)#
public class Thing implements Cloneable{
private ArrayList<String> arrayList = new ArrayList<String>();
@Override
public Thing clone() {
//通過(guò)繼承Cloneable接口伴网,實(shí)現(xiàn)clone方法
Thing thing = null;
try {
thing = (Thing) super.clone();
//深拷貝問(wèn)題解決
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;
}
}