最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java設(shè)計(jì)模式--原型模式詳解

 更新時(shí)間:2021年07月19日 15:32:52   作者:吾仄lo咚鏘  
這篇文章主要為大家詳細(xì)介紹了Java設(shè)計(jì)模式之Prototype原型模式的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

引例

問題:

現(xiàn)在有一只羊(包含屬性:名字Dolly、年齡2),需要克隆10只屬性完全相同的羊。

一般解法:

定義Sheep類表示羊,包括構(gòu)造器、getter()和toString()。

public class Sheep {
    private String name;
    private int age;
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

在客戶端實(shí)例化多利,然后再根據(jù)多利的屬性去實(shí)例化10只羊。

public class Client {
    public static void main(String[] args) {
        Sheep sheepDolly=new Sheep("Dolly",2);
        Sheep sheep1 = new Sheep(sheepDolly.getName(), sheepDolly.getAge());
        Sheep sheep2 = new Sheep(sheepDolly.getName(), sheepDolly.getAge());
        Sheep sheep3 = new Sheep(sheepDolly.getName(), sheepDolly.getAge());
        //....
        System.out.println(sheep1+",hashCode:"+sheep1.hashCode());
        System.out.println(sheep2+",hashCode:"+sheep2.hashCode());
        System.out.println(sheep3+",hashCode:"+sheep3.hashCode());
        //...
    }
}

運(yùn)行結(jié)果

在這里插入圖片描述

優(yōu)缺點(diǎn):

這種方法是我們首先很容易就能想到的,也是絕大多數(shù)人的第一做法。

但缺點(diǎn)也很明顯,每次創(chuàng)建新對象時(shí)需要獲取原始對象的屬性,對象復(fù)雜時(shí)效率很低;此外不能動(dòng)態(tài)獲得對象運(yùn)行時(shí)的狀態(tài),若類增減屬性需要改動(dòng)代碼。

下面我們看下原型模式的解法。

原型模式

原型模式(Prototype Pattern)是一種創(chuàng)建型設(shè)計(jì)模式,允許一個(gè)對象再創(chuàng)建另外一個(gè)可定制的對象,無需知道如何創(chuàng)建的細(xì)節(jié)。即用原型實(shí)例指定創(chuàng)建對象的種類,并且通過拷貝這些原型,創(chuàng)建新的對象。

工作原理:將原型對象傳給那個(gè)要發(fā)動(dòng)創(chuàng)建的對象,這個(gè)要發(fā)動(dòng)創(chuàng)建的對象通過請求原型對象拷貝它們自己來實(shí)施創(chuàng)建。即用基類Object的clone()方法或序列化。

UML類圖:

在這里插入圖片描述

  • Prototype:原型類,聲明一個(gè)克隆自己的接口
  • ConcretePrototype: 具體的原型類, 實(shí)現(xiàn)一個(gè)克隆自己的操作
  • Client: 客戶端讓一個(gè)原型對象克隆自己,從而創(chuàng)建一個(gè)新的對象

原型模式又可分為淺拷貝和深拷貝,區(qū)別在于對引用數(shù)據(jù)類型的成員變量的拷貝,小朋友你是否有很多問號? 不急 ,看完這兩種方法實(shí)現(xiàn)你就懂了。

淺拷貝

在原先Sheep類基礎(chǔ)上實(shí)現(xiàn)Cloneable接口,重寫clone方法。

public class Sheep implements Cloneable{
    private String name;
    private int age;
    @Override
    protected Object clone()  {//克隆該實(shí)例,使用默認(rèn)的clone方法來完成
        Sheep sheep = null;
        try {
            sheep = (Sheep)super.clone();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sheep;
    }
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

客戶端調(diào)用

public class Client {
    public static void main(String[] args) {
        Sheep sheepDolly=new Sheep("Dolly",2);
        Sheep sheep1 = (Sheep)sheepDolly.clone();
        Sheep sheep2 = (Sheep)sheepDolly.clone();
        Sheep sheep3 = (Sheep)sheepDolly.clone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        //...
    }
}

運(yùn)行結(jié)果

在這里插入圖片描述

至此,原型模式的淺拷貝也成功克隆了三個(gè)對象,但是看進(jìn)度條發(fā)現(xiàn)并不簡單。

現(xiàn)在小羊有了一個(gè)朋友小牛,Sheep類添加了一個(gè)引用屬性Cow,我們同樣再克隆一遍。

Sheep類

public class Sheep implements Cloneable{
    private String name;
    private int age;
    public Cow friend;//新朋友Cow對象,其余不變
    @Override
    protected Object clone()  {
        Sheep sheep = null;
        try {
            sheep = (Sheep)super.clone();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sheep;
    }
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

新添的Cow類

public class Cow {
    private String name;
    private int age;
    public Cow(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Cow{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

客戶端調(diào)用克隆

public class Client {
    public static void main(String[] args) {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并實(shí)例化朋友
        Sheep sheep1 = (Sheep)sheepDolly.clone();
        Sheep sheep2 = (Sheep)sheepDolly.clone();
        Sheep sheep3 = (Sheep)sheepDolly.clone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep1.friend:"+sheep1.friend+",hashCode:" + sheep1.friend.hashCode()+'\n');
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep2.friend:"+sheep2.friend+",hashCode:" + sheep2.friend.hashCode()+'\n');
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        System.out.println("sheep3.friend:"+sheep3.friend+",hashCode:" + sheep3.friend.hashCode()+'\n');
        //...
    }
}

運(yùn)行結(jié)果

在這里插入圖片描述

通過運(yùn)行結(jié)果發(fā)現(xiàn),淺拷貝通過Object的clone()成功克隆實(shí)例化了三個(gè)新對象,但是并沒有克隆實(shí)例化對象中的引用屬性,也就是沒有克隆friend對象(禁止套娃 ),三個(gè)新克隆對象的friend還是指向原克隆前的friend,即同一個(gè)對象。

這樣的話,他們四個(gè)的friend是引用同一個(gè),若一個(gè)對象修改了friend屬性,勢必會影響其他三個(gè)對象的該成員變量值。

小結(jié):

  • 淺拷貝是使用默認(rèn)的 clone()方法來實(shí)現(xiàn)
  • 基本數(shù)據(jù)類型的成員變量,淺拷貝會直接進(jìn)行值傳遞(復(fù)制屬性值給新對象)。
  • 引用數(shù)據(jù)類型的成員變量,淺拷貝會進(jìn)行引用傳遞(復(fù)制引用值(內(nèi)存地址)給新對象)。

深拷貝

方法一:

機(jī)靈的人兒看出,再clone一遍cow不就好了,但是手動(dòng)遞歸下去不推薦。

1.Cow類也實(shí)現(xiàn)Cloneable接口

public class Cow implements Cloneable{
    private String name;
    private int age;
    public Cow(String name, int age) {
        this.name = name;
        this.age = age;
    }
    //無引用類型,直接clone即可
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); //直接拋出了,沒用try-catch
    }
    @Override
    public String toString() {
        return "Cow{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Sheep類的clone再添加調(diào)用cow的clone

public class Sheep implements Cloneable{
    private String name;
    private int age;
    public Cow friend;//新朋友Cow對象,其余不變
    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        //完成對基本數(shù)據(jù)類型(屬性)和String的克隆
        deep = super.clone();
        //對引用類型的屬性,進(jìn)行再次clone
        Sheep sheep = (Sheep)deep;
        sheep.friend  = (Cow)friend.clone();
        return sheep;
    }
    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

客戶端調(diào)用

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并實(shí)例化朋友
        Sheep sheep1 = (Sheep)sheepDolly.clone();
        Sheep sheep2 = (Sheep)sheepDolly.clone();
        Sheep sheep3 = (Sheep)sheepDolly.clone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep1.friend:"+sheep1.friend+",hashCode:" + sheep1.friend.hashCode()+'\n');
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep2.friend:"+sheep2.friend+",hashCode:" + sheep2.friend.hashCode()+'\n');
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        System.out.println("sheep3.friend:"+sheep3.friend+",hashCode:" + sheep3.friend.hashCode()+'\n');
        //...
    }
}

運(yùn)行結(jié)果

在這里插入圖片描述

方法二:

通過對象序列化實(shí)現(xiàn)深拷貝(推薦)

1.Cow類實(shí)現(xiàn)序列化接口,不必實(shí)現(xiàn)Cloneable接口了

public class Cow implements Serializable {
    private String name;
    private int age;
    public Cow(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Cow{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

2.在Sheep類實(shí)現(xiàn)序列化接口

public class Sheep implements Serializable { //實(shí)現(xiàn)序列化接口
    private String name;
    private int age;
    public Cow friend;

    public Sheep(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public String toString() {
        return "Sheep{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
    public Object deepClone() { //深拷貝
        //創(chuàng)建流對象
        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è)對象以對象流的方式輸出
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            Sheep sheep = (Sheep) ois.readObject();
            return sheep;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //關(guān)閉流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e2) {
                System.out.println(e2.getMessage());
            }
        }
    }
}

3.客戶端調(diào)用

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并實(shí)例化朋友
        Sheep sheep1 = (Sheep)sheepDolly.deepClone();
        Sheep sheep2 = (Sheep)sheepDolly.deepClone();
        Sheep sheep3 = (Sheep)sheepDolly.deepClone();
        //....
        System.out.println("sheep1:"+sheep1+",hashCode:" + sheep1.hashCode());
        System.out.println("sheep1.friend:"+sheep1.friend+",hashCode:" + sheep1.friend.hashCode()+'\n');
        System.out.println("sheep2:"+sheep2+",hashCode:" + sheep2.hashCode());
        System.out.println("sheep2.friend:"+sheep2.friend+",hashCode:" + sheep2.friend.hashCode()+'\n');
        System.out.println("sheep3:"+sheep3+",hashCode:" + sheep3.hashCode());
        System.out.println("sheep3.friend:"+sheep3.friend+",hashCode:" + sheep3.friend.hashCode()+'\n');
        //...
    }
}

運(yùn)行結(jié)果

在這里插入圖片描述

原型模式總結(jié):

  • 創(chuàng)建新的對象比較復(fù)雜時(shí),可以利用原型模式簡化對象的創(chuàng)建過程,同時(shí)也能夠提高效率
  • 可以不用重新初始化對象,動(dòng)態(tài)地獲得對象運(yùn)行時(shí)的狀態(tài)。
  • 如果原始對象發(fā)生變化(增加或者減少屬性),其它克隆對象的也會發(fā)生相應(yīng)的變化,無需修改代碼
  • 若成員變量無引用類型,淺拷貝clone即可;若引用類型的成員變量很少,可考慮遞歸實(shí)現(xiàn)clone,否則推薦序列化。

總結(jié)

本篇文章就到這里了,希望能給你帶來幫助,也希望您能夠多多關(guān)注腳本之家的更多內(nèi)容!

相關(guān)文章

  • Java結(jié)構(gòu)型設(shè)計(jì)模式之組合模式詳解

    Java結(jié)構(gòu)型設(shè)計(jì)模式之組合模式詳解

    組合模式,又叫部分整體模式,它創(chuàng)建了對象組的數(shù)據(jù)結(jié)構(gòu)組合模式使得用戶對單個(gè)對象和組合對象的訪問具有一致性。本文將通過示例為大家詳細(xì)介紹一下組合模式,需要的可以參考一下
    2022-09-09
  • JavaWeb實(shí)戰(zhàn)之用Servlet+JDBC實(shí)現(xiàn)用戶登錄與注冊

    JavaWeb實(shí)戰(zhàn)之用Servlet+JDBC實(shí)現(xiàn)用戶登錄與注冊

    這篇文章主要介紹了JavaWeb實(shí)戰(zhàn)之用Servlet+JDBC實(shí)現(xiàn)用戶登錄與注冊,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有很大的幫助,需要的朋友可以參考下
    2021-04-04
  • SpringBoot?Mail郵件任務(wù)詳情

    SpringBoot?Mail郵件任務(wù)詳情

    這篇文章主要介紹了SpringBoot?Mail郵件任務(wù)詳情,文章通過spring-boot-starter-mail包展開詳細(xì)內(nèi)容,需要的小伙伴可以參考一下
    2022-05-05
  • Java調(diào)用linux shell腳本的方法

    Java調(diào)用linux shell腳本的方法

    這篇文章主要介紹了Java調(diào)用linux shell腳本的方法,需要的朋友可以參考下
    2015-02-02
  • Java內(nèi)存模型相關(guān)知識總結(jié)

    Java內(nèi)存模型相關(guān)知識總結(jié)

    這篇文章主要介紹了Java內(nèi)存模型相關(guān)知識總結(jié),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-10-10
  • Maven使用Nexus創(chuàng)建私服的實(shí)現(xiàn)

    Maven使用Nexus創(chuàng)建私服的實(shí)現(xiàn)

    本文主要介紹了Maven使用Nexus創(chuàng)建私服的實(shí)現(xiàn),通過建立自己的私服,就可以降低中央倉庫負(fù)荷、節(jié)省外網(wǎng)帶寬、加速M(fèi)aven構(gòu)建、自己部署構(gòu)件等,從而高效地使用Maven,感興趣的可以了解一下
    2024-04-04
  • Java中List集合的常用方法詳解

    Java中List集合的常用方法詳解

    本篇文章給大家?guī)淼膬?nèi)容是關(guān)于Java中List集合的常用方法詳解,有一定的參考價(jià)值,有需要的朋友可以參考一下,希望對你有所幫助。下面我們就來學(xué)習(xí)一下吧
    2021-11-11
  • MyBatis 多表查詢?nèi)N最常見的寫法

    MyBatis 多表查詢?nèi)N最常見的寫法

    這篇文章主要介紹了MyBatis 多表查詢?nèi)N最常見的寫法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2025-04-04
  • springboot集成gzip和zip數(shù)據(jù)壓縮傳輸(適用大數(shù)據(jù)信息傳輸)

    springboot集成gzip和zip數(shù)據(jù)壓縮傳輸(適用大數(shù)據(jù)信息傳輸)

    ?在大數(shù)據(jù)量的傳輸中,壓縮數(shù)據(jù)后進(jìn)行傳輸可以一定程度的解決速度問題,本文主要介紹了springboot集成gzip和zip數(shù)據(jù)壓縮傳輸,具有一定的參考價(jià)值,感興趣的可以了解一下
    2023-09-09
  • Logger.getLogger()與LogFactory.getLog()的區(qū)別詳解

    Logger.getLogger()與LogFactory.getLog()的區(qū)別詳解

    LogFactory來自common-logging包。如果用LogFactory.getLog,你可以用任何實(shí)現(xiàn)了通用日志接口的日志記錄器替換log4j,而程序不受影響
    2013-09-09

最新評論

江门市| 黔南| 平凉市| 黎川县| 湖州市| 亚东县| 芜湖市| 天津市| 额尔古纳市| 古浪县| 观塘区| 平江县| 云梦县| 美姑县| 平昌县| 辛集市| 扶沟县| 建德市| 大余县| 新化县| 石城县| 尖扎县| 南康市| 兴和县| 美姑县| 鹤岗市| 朝阳县| 大悟县| 盐城市| 巫溪县| 麻城市| 遵义市| 调兵山市| 运城市| 定襄县| 凤冈县| 安平县| 安龙县| 正定县| 广州市| 涞水县|