欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java設計模式--原型模式詳解

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

引例

問題:

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

一般解法:

定義Sheep類表示羊,包括構造器、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 +
                '}';
    }
}

在客戶端實例化多利,然后再根據(jù)多利的屬性去實例化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ōu)缺點:

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

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

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

原型模式

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

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

UML類圖:

在這里插入圖片描述

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

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

淺拷貝

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

public class Sheep implements Cloneable{
    private String name;
    private int age;
    @Override
    protected Object clone()  {//克隆該實例,使用默認的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 +
                '}';
    }
}

客戶端調用

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());
        //...
    }
}

運行結果

在這里插入圖片描述

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

現(xiàn)在小羊有了一個朋友小牛,Sheep類添加了一個引用屬性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 +
                '}';
    }
}

客戶端調用克隆

public class Client {
    public static void main(String[] args) {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并實例化朋友
        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');
        //...
    }
}

運行結果

在這里插入圖片描述

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

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

小結:

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

深拷貝

方法一:

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

1.Cow類也實現(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再添加調用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();
        //對引用類型的屬性,進行再次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 +
                '}';
    }
}

客戶端調用

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并實例化朋友
        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');
        //...
    }
}

運行結果

在這里插入圖片描述

方法二:

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

1.Cow類實現(xiàn)序列化接口,不必實現(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類實現(xiàn)序列化接口

public class Sheep implements Serializable { //實現(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); //當前這個對象以對象流的方式輸出
            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            Sheep sheep = (Sheep) ois.readObject();
            return sheep;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //關閉流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e2) {
                System.out.println(e2.getMessage());
            }
        }
    }
}

3.客戶端調用

public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        Sheep sheepDolly=new Sheep("Dolly",2);
        sheepDolly.friend=new Cow("Tom",1); //并實例化朋友
        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');
        //...
    }
}

運行結果

在這里插入圖片描述

原型模式總結:

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

總結

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

相關文章

  • jdbc和mybatis的流式查詢使用方法

    jdbc和mybatis的流式查詢使用方法

    有些時候我們所需要查詢的數(shù)據(jù)量比較大,但是jvm內存又是有限制的,數(shù)據(jù)量過大會導致內存溢出。這個時候就可以使用流式查詢,本文就主要介紹了jdbc和mybatis的流式查詢,感興趣的可以了解一下
    2021-11-11
  • SpringBoot中Mockito單元測試入門

    SpringBoot中Mockito單元測試入門

    單元測試在很多地方都用的到,本文主要介紹了SpringBoot中Mockito單元測試入門,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-06-06
  • java分頁攔截類實現(xiàn)sql自動分頁

    java分頁攔截類實現(xiàn)sql自動分頁

    這篇文章主要為大家詳細介紹了java分頁攔截類可以實現(xiàn)sql自動分頁,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2016-11-11
  • Java通過調用C/C++實現(xiàn)的DLL動態(tài)庫——JNI的方法

    Java通過調用C/C++實現(xiàn)的DLL動態(tài)庫——JNI的方法

    這篇文章主要介紹了Java通過調用C/C++實現(xiàn)的DLL動態(tài)庫——JNI的方法,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2018-01-01
  • MyBatis在mapper中傳遞參數(shù)的四種方式

    MyBatis在mapper中傳遞參數(shù)的四種方式

    MyBatis是一個持久層框架,它提供了一種將數(shù)據(jù)庫操作與Java對象之間的映射關系進行配置的方式,在MyBatis中,Mapper是用于定義數(shù)據(jù)庫操作的接口,而參數(shù)傳遞則是通過Mapper接口的方法來實現(xiàn)的,本文給大家介紹了MyBatis在mapper中傳遞參數(shù)的四種方式,需要的朋友可以參考下
    2024-03-03
  • java-SSH2實現(xiàn)數(shù)據(jù)庫和界面的分頁

    java-SSH2實現(xiàn)數(shù)據(jù)庫和界面的分頁

    本文主要是介紹SSH2實現(xiàn)數(shù)據(jù)庫和界面的分頁的代碼,分頁在web應用中是經常要做的事情,實用性比較大,有需要的朋友可以來了解一下。
    2016-10-10
  • java實現(xiàn)百度云OCR文字識別 高精度OCR識別身份證信息

    java實現(xiàn)百度云OCR文字識別 高精度OCR識別身份證信息

    這篇文章主要為大家詳細介紹了java實現(xiàn)百度云OCR文字識別,高精度OCR識別身份證信息,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • IDEA 每次新建工程都要重新配置 Maven的解決方案

    IDEA 每次新建工程都要重新配置 Maven的解決方案

    這篇文章主要介紹了IDEA 每次新建工程都要重新配置Maven解決方案,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-05-05
  • Java基于正則表達式實現(xiàn)查找匹配的文本功能【經典實例】

    Java基于正則表達式實現(xiàn)查找匹配的文本功能【經典實例】

    這篇文章主要介紹了Java基于正則表達式實現(xiàn)查找匹配的文本功能,結合具體實例形式分析了java正則查找、字符串遍歷、group分組相關操作技巧,需要的朋友可以參考下
    2017-04-04
  • Java集合List的使用詳細解析

    Java集合List的使用詳細解析

    這篇文章主要介紹了Java集合List的使用詳細解析,List集合類中元素有序、且可重復,集合中的每個元素都有其對應的順序索引,鑒于Java中數(shù)組用來存儲數(shù)據(jù)的局限性,我們通常使用java.util.List替代數(shù)組,需要的朋友可以參考下
    2023-11-11

最新評論