Java 深入探討設(shè)計(jì)模式之原型模式篇
傳統(tǒng)方式
克隆羊問題
現(xiàn)在有一只羊 tom,姓名為: tom,年齡為:1,顏色為:白色,請(qǐng)編寫程序創(chuàng)建和 tom羊?qū)傩酝耆嗤?0只羊。
傳統(tǒng)方式解決克隆羊問題
思路分析(圖解)

代碼演示:
public class Sheep {
private String name;
private int age;
private String color;
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Sheep [name=" + name + ", age=" + age + ", color=" + color + "]";
}
}
public class Client {
public static void main(String[] args) {
// TODO Auto-generated method stub
//傳統(tǒng)方法
Sheep sheep = new Sheep("tom", 1, "白色 ");
Sheep sheep2 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep3 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep4 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
Sheep sheep5 = new Sheep(sheep.getName(), sheep.getAge(), sheep.getColor());
//....
System.out.println(sheep);
System.out.println(sheep2);
System.out.println(sheep3);
System.out.println(sheep4);
System.out.println(sheep5);
//...
}
}
傳統(tǒng)方式的優(yōu)缺點(diǎn)
①優(yōu)點(diǎn)是比較好理解,簡(jiǎn)單易操作。
②在創(chuàng)建新的對(duì)象時(shí),總是需要重新獲取原始對(duì)象的屬性,如果創(chuàng)建的對(duì)象比較復(fù)雜時(shí),效率較低
③總是需要重新初始化對(duì)象,而不是動(dòng)態(tài)地獲得對(duì)象運(yùn)行時(shí)的狀態(tài),不夠靈活
④改進(jìn)的思路分析
思路:Java中 Object類是所有類的根類,Object類提供了一個(gè)clone()方法,該方法可以將一個(gè)Java對(duì)象復(fù)制一份,但是需要實(shí)現(xiàn)clone的Java類必須要實(shí)現(xiàn)一個(gè)接口Cloneable,該接口表示該類能夠復(fù)制且具有復(fù)制的能力
原型模式基本介紹
①原型模式(Prototype模式)是指:用原型實(shí)例指定創(chuàng)建對(duì)象的種類,并且通過拷貝這些原型,創(chuàng)建新的對(duì)象
②原型模式是一種創(chuàng)建型設(shè)計(jì)模式,允許一個(gè)對(duì)象再創(chuàng)建另外一個(gè)可定制的對(duì)象,無需知道如何創(chuàng)建的細(xì)節(jié)
③工作原理是:通過將一個(gè)原型對(duì)象傳給那個(gè)要發(fā)動(dòng)創(chuàng)建的對(duì)象,這個(gè)要發(fā)動(dòng)創(chuàng)建的對(duì)象通過請(qǐng)求原型對(duì)象拷貝它們自己來實(shí)施創(chuàng)建,即對(duì)象.clone()
④形象的理解:孫大圣拔出猴毛,變出其它孫大圣
原型模式原理結(jié)構(gòu)圖-uml圖

原理結(jié)構(gòu)圖說明
Prototype :原型類,聲明一個(gè)克隆自己的接口
ConcretePrototype:具體的原型類,實(shí)現(xiàn)一個(gè)克隆自己的操作
Client:讓一個(gè)原型對(duì)象克隆自己,從而創(chuàng)建一個(gè)新的對(duì)象(屬性一樣)
原型模式解決克隆羊問題的應(yīng)用實(shí)例
使用原型模式改進(jìn)傳統(tǒng)方式,讓程序具有更高的效率和擴(kuò)展性。
代碼演示:
public class Sheep implements Cloneable {
private String name;
private int age;
private String color;
private String address = "蒙古羊";
public Sheep friend; //
public Sheep(String name, int age, String color) {
super();
this.name = name;
this.age = age;
this.color = color;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
@Override
public String toString() {
return "Sheep [name=" + name + ", age=" + age + ", color=" + color + ", address=" + address + "]";
}
//克隆該實(shí)例,使用默認(rèn)的構(gòu)造方法來完成
@Override
protected Object clone() {
Sheep sheep = null;
try {
sheep = (Sheep)super.clone();
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
// TODO Auto-generated method stub
return sheep;
}
}
public class Client {
public static void main(String[] args) {
System.out.println("原型模式完成對(duì)象的創(chuàng)建");
// TODO Auto-generated method stub
Sheep sheep = new Sheep("tom", 1, "白色 ");
sheep.friend = new Sheep("jack", 2, "藍(lán)色");
Sheep sheep2 = (Sheep)sheep.clone(); //克隆
Sheep sheep3 = (Sheep)sheep.clone(); //克隆
Sheep sheep4 = (Sheep)sheep.clone(); //克隆
Sheep sheep5 = (Sheep)sheep.clone(); //克隆
System.out.println("sheep2 =" + sheep2 + "sheep2.friend=" + sheep2.friend.hashCode());
System.out.println("sheep3 =" + sheep3 + "sheep3.friend=" + sheep3.friend.hashCode());
System.out.println("sheep4 =" + sheep4 + "sheep4.friend=" + sheep4.friend.hashCode());
System.out.println("sheep5 =" + sheep5 + "sheep5.friend=" + sheep5.friend.hashCode());
}
}
原型模式在spring框架中源碼分析
Spring 中原型bean 的創(chuàng)建,就是原型模式的應(yīng)用

深入討論-淺討論和深拷貝
淺拷貝基本介紹
①對(duì)于數(shù)據(jù)類型是基本數(shù)據(jù)類型的成員變量,淺拷貝會(huì)直接進(jìn)行值傳遞,也就是將該屬性值復(fù)制一份給新的對(duì)象。
②對(duì)于數(shù)據(jù)類型是引用數(shù)據(jù)類型的成員變量,比如說成員變量是某個(gè)數(shù)組、某個(gè)類的對(duì)象等,那么淺拷貝會(huì)進(jìn)行引用傳遞,也就是只是將該成員變量的引用值〈內(nèi)存地址)復(fù)制一份給新的對(duì)象。因?yàn)閷?shí)際上兩個(gè)對(duì)象的該成員變量都指向同一個(gè)實(shí)例。在這種情況下,在一個(gè)對(duì)象中修改該成員變量會(huì)影響到另一個(gè)對(duì)象的該成員變量值
③前面的克隆羊就是淺拷貝
④淺拷貝是使用默認(rèn)的clone()方法來實(shí)現(xiàn),sheep= (Sheep) super.clone();
深拷貝基本介紹
①?gòu)?fù)制對(duì)象的所有基本數(shù)據(jù)類型的成員變量值
②為所有引用數(shù)據(jù)類型的成員變量申請(qǐng)存儲(chǔ)空間,并復(fù)制每個(gè)引用數(shù)據(jù)類型成員變量所引用的對(duì)象,直到該對(duì)象可達(dá)的所有對(duì)象。也就是說,對(duì)象進(jìn)行深拷貝要對(duì)整個(gè)對(duì)象(包括對(duì)象的引用類型)進(jìn)行拷貝
③深拷貝實(shí)現(xiàn)方式1:重寫clone方法來實(shí)現(xiàn)深拷貝
④深拷貝實(shí)現(xiàn)方式2:通過對(duì)象序列化實(shí)現(xiàn)深拷貝(推薦)
深拷貝應(yīng)用案例;
①使用重寫clone方法實(shí)現(xiàn)深拷貝
②使用序列化來實(shí)現(xiàn)深拷貝
③代碼演示
public class DeepProtoType implements Serializable, Cloneable{
public String name; //String屬性
public DeepCloneableTarget deepCloneableTarget;//引用類型
public DeepProtoType() {
super();
}
//深拷貝實(shí)現(xiàn)方式1:重寫clone方法來實(shí)現(xiàn)深拷貝
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
//這里完成對(duì)基本數(shù)據(jù)類型(屬性)和String的克隆
deep = super.clone();
//對(duì)引用類型的屬性,進(jìn)行單獨(dú)處理
DeepProtoType deepProtoType = (DeepProtoType)deep;
deepProtoType.deepCloneableTarget = (DeepCloneableTarget)deepCloneableTarget.clone();
// TODO Auto-generated method stub
return deepProtoType;
}
//深拷貝實(shí)現(xiàn)方式2:通過對(duì)象序列化實(shí)現(xiàn)深拷貝
public Object deepClone() {
//創(chuàng)建流對(duì)象
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
//序列化
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this); //當(dāng)前這個(gè)對(duì)象以對(duì)象流的方式輸出
//反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
DeepProtoType copyObj = (DeepProtoType)ois.readObject();
return copyObj;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
} finally {
//關(guān)閉流
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (Exception e2) {
// TODO: handle exception
System.out.println(e2.getMessage());
}
}
}
}
public class DeepCloneableTarget implements Serializable, Cloneable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String cloneName;
private String cloneClass;
//構(gòu)造器
public DeepCloneableTarget(String cloneName, String cloneClass) {
this.cloneName = cloneName;
this.cloneClass = cloneClass;
}
//因?yàn)樵擃惖膶傩?,都是String,因此我們這里使用默認(rèn)的clone完成即可
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Client {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
DeepProtoType p = new DeepProtoType();
p.name = "宋江";
p.deepCloneableTarget = new DeepCloneableTarget("大牛", "小牛的類");
//方式1完成深拷貝
// DeepProtoType p2 = (DeepProtoType) p.clone();
//
// System.out.println("p.name=" + p.name + "p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
// System.out.println("p2.name=" + p.name + "p2.deepCloneableTarget=" + p2.deepCloneableTarget.hashCode());
//方式2完成深拷貝
DeepProtoType p2 = (DeepProtoType) p.deepClone();
System.out.println("p.name=" + p.name + "p.deepCloneableTarget=" + p.deepCloneableTarget.hashCode());
System.out.println("p2.name=" + p.name + "p2.deepCloneableTarget=" + p2.deepCloneableTarget.hashCode());
}
}
原型模式的注意事項(xiàng)和細(xì)節(jié)
①創(chuàng)建新的對(duì)象比較復(fù)雜時(shí),可以利用原型模式簡(jiǎn)化對(duì)象的創(chuàng)建過程,同時(shí)也能夠提高效率
②不用重新初始化對(duì)象,而是動(dòng)態(tài)地獲得對(duì)象運(yùn)行時(shí)的狀態(tài)
③如果原始對(duì)象發(fā)生變化(增加或者減少屬性),其它克隆對(duì)象的也會(huì)發(fā)生相應(yīng)的變化,無需修改代碼
④在實(shí)現(xiàn)深克隆的時(shí)候可能需要比較復(fù)雜的代碼
⑤缺點(diǎn):需要為每一個(gè)類配備一個(gè)克隆方法,這對(duì)全新的類來說不是很難,但對(duì)已有的類進(jìn)行改造時(shí),需要修改其源代碼,違背了ocp原則,這點(diǎn)請(qǐng)同學(xué)們注意。
到此這篇關(guān)于Java 深入探討設(shè)計(jì)模式之原型模式篇的文章就介紹到這了,更多相關(guān)Java 設(shè)計(jì)模式內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java連接合并2個(gè)數(shù)組(Array)的5種方法例子
最近在寫代碼時(shí)遇到了需要合并兩個(gè)數(shù)組的需求,突然發(fā)現(xiàn)以前沒用過,于是研究了一下合并數(shù)組的方式,這篇文章主要給大家介紹了關(guān)于Java連接合并2個(gè)數(shù)組(Array)的5種方法,需要的朋友可以參考下2023-12-12
SpringDataMongoDB多文檔事務(wù)的實(shí)現(xiàn)
mongodb4.0也出來一段時(shí)間了,這個(gè)版本最為大眾期待的特性就是支持了多文檔事務(wù)。這篇文章主要介紹了SpringDataMongoDB多文檔事務(wù)的實(shí)現(xiàn),感興趣的小伙伴們可以參考一下2018-11-11
Java版仿QQ驗(yàn)證碼風(fēng)格圖片驗(yàn)證碼
這篇文章主要為大家分享了java圖片驗(yàn)證碼實(shí)例代碼,感興趣的小伙伴們可以參考一下2016-04-04
Java實(shí)現(xiàn)房屋出租系統(tǒng)詳解
這篇文章主要介紹了實(shí)現(xiàn)Java房屋出租系統(tǒng)的實(shí)現(xiàn)過程,文章條理清晰,在實(shí)現(xiàn)過程中加深了對(duì)相關(guān)概念的理解,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-10-10
Go?Java算法之為運(yùn)算表達(dá)式設(shè)計(jì)優(yōu)先級(jí)實(shí)例
這篇文章主要為大家介紹了Go?Java算法之為運(yùn)算表達(dá)式設(shè)計(jì)優(yōu)先級(jí)實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
SpringBoot+Dubbo+Seata分布式事務(wù)實(shí)戰(zhàn)詳解
這篇文章主要介紹了SpringBoot+Dubbo+Seata分布式事務(wù)實(shí)戰(zhàn)詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07
IDEA創(chuàng)建Servlet并配置web.xml的實(shí)現(xiàn)
這篇文章主要介紹了IDEA創(chuàng)建Servlet并配置web.xml的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

