原型模式 java 深浅_Java设计模式——原型模式
原型模式(Prototype)
原型模式雖然是創(chuàng)建型的模式,但是與工程模式?jīng)]有關(guān)系,從名字即可看出,該模式的思想就是將一個(gè)對象作為原型,對其進(jìn)行復(fù)制、克隆,產(chǎn)生一個(gè)和原對象類似的新對象。本小結(jié)會通過對象的復(fù)制,進(jìn)行講解。在Java中,復(fù)制對象是通過clone()實(shí)現(xiàn)的,先創(chuàng)建一個(gè)原型類:
public class Prototype implements Cloneable {
public Object clone() throws CloneNotSupportedException {
Prototype proto = (Prototype) super.clone();
return proto;
}
}
很簡單,一個(gè)原型類,只需要實(shí)現(xiàn)Cloneable接口,覆寫clone方法,此處clone方法可以改成任意的名稱,因?yàn)镃loneable接口是個(gè)空接口,你可以任意定義實(shí)現(xiàn)類的方法名,如cloneA或者cloneB,因?yàn)榇颂幍闹攸c(diǎn)是super.clone()這句話,super.clone()調(diào)用的是Object的clone()方法,而在Object類中,clone()是native的,這是對Java中本地方法的調(diào)用。在這兒,我將結(jié)合對象的淺復(fù)制和深復(fù)制來說一下,首先需要了解對象深、淺復(fù)制的概念:
淺復(fù)制:將一個(gè)對象復(fù)制后,基本數(shù)據(jù)類型的變量都會重新創(chuàng)建,而引用類型,指向的還是原對象所指向的。
深復(fù)制:將一個(gè)對象復(fù)制后,不論是基本數(shù)據(jù)類型還有引用類型,都是重新創(chuàng)建的。簡單來說,就是深復(fù)制進(jìn)行了完全徹底的復(fù)制,而淺復(fù)制不徹底。
此處,寫一個(gè)深淺復(fù)制的例子:
public class Prototype implements Cloneable, Serializable {
private static final long serialVersionUID = 1L;
private String string;
private SerializableObject obj;
/* 淺復(fù)制 */
public Object clone() throws CloneNotSupportedException {
Prototype proto = (Prototype) super.clone();
return proto;
}
/* 深復(fù)制 */
public Object deepClone() throws IOException, ClassNotFoundException {
/* 寫入當(dāng)前對象的二進(jìn)制流 */
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
/* 讀出二進(jìn)制流產(chǎn)生的新對象 */
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public SerializableObject getObj() {
return obj;
}
public void setObj(SerializableObject obj) {
this.obj = obj;
}
}
class SerializableObject implements Serializable {
private static final long serialVersionUID = 1L;
}
要實(shí)現(xiàn)深復(fù)制,需要采用流的形式讀入當(dāng)前對象的二進(jìn)制輸入,再寫出二進(jìn)制數(shù)據(jù)對應(yīng)的對象。
總結(jié)
以上是生活随笔為你收集整理的原型模式 java 深浅_Java设计模式——原型模式的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [云炬学英语]每日一句2020.9.1
- 下一篇: [云炬学英语]每日一句2020.9.3