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

淺談Java設計模式之原型模式知識總結

 更新時間:2021年05月26日 08:40:48   作者:喲喲之名  
Java原型模式主要用于創(chuàng)建重復的對象,同時又能保證性能,這篇文章就帶大家仔細了解一下原型模式的知識,對正在學習java的小伙伴們很有幫助,需要的朋友可以參考下

如何使用?

1.首先定義一個User類,它必須實現(xiàn)了Cloneable接口,重寫了clone()方法。

public class User implements Cloneable {
    private String name;
    private int age;
    private Brother brother;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

2.Brother類

public class Brother{
	private String name;
}

3.應用演示類

public class PrototypeDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        User user1 = new User();
        user1.setName("秋紅葉");
        user1.setAge(20);
        Brother brother1 = new Brother();
        brother1.setName("七夜圣君");
        user1.setBrother(brother1);
        // 我們從克隆對象user2中修改brother,看看是否會影響user1的brother
        User user2 = (User) user1.clone();
        user2.setName("燕赤霞");
        Brother brother2 = user2.getBrother();
        brother2.setName("唐鈺小寶");
        System.out.println(user1);
        System.out.println(user2);
        System.out.println(user1.getBrother() == user2.getBrother());
    }
}

在這里插入圖片描述

4.深拷貝寫法

這是User類

public class User implements Cloneable {
    private String name;
    private int age;
    private Brother brother;

	/**
	* 主要就是看這個重寫的方法,需要將brother也進行clone
	*/
    @Override
    protected Object clone() throws CloneNotSupportedException {
        User user = (User) super.clone();
        user.brother = (Brother) this.brother.clone();
        return user;
    }
}

這是Brother類

public class Brother implements Cloneable{
    private String name;

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

這里是結果演示

public class PrototypeDemo {
    public static void main(String[] args) throws CloneNotSupportedException {
        User user1 = new User();
        user1.setName("秋紅葉");
        user1.setAge(20);
        Brother brother1 = new Brother();
        brother1.setName("七夜圣君");
        user1.setBrother(brother1);
		// 我們從克隆對象user2中修改brother,看看是否會影響user1的brother
        User user2 = (User) user1.clone();
        user2.setName("燕赤霞");
        Brother brother2 = user2.getBrother();
        brother2.setName("唐鈺小寶");
        System.out.println(user1);
        System.out.println(user2);
        System.out.println(user1.getBrother() == user2.getBrother());
    }
}

在這里插入圖片描述

可以看到,user1的brother沒有受到user2的影響,深拷貝成功!

5.圖解深拷貝與淺拷貝

在這里插入圖片描述

總結與思考

java中object類的clone()方法為淺拷貝必須實現(xiàn)Cloneable接口如果想要實現(xiàn)深拷貝,則需要重寫clone()方法

到此這篇關于淺談Java設計模式之原型模式知識總結的文章就介紹到這了,更多相關Java原型模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論