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

淺談Java設(shè)計(jì)模式之原型模式知識(shí)總結(jié)

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

如何使用?

1.首先定義一個(gè)User類(lèi),它必須實(shí)現(xiàn)了Cloneable接口,重寫(xiě)了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類(lèi)

public class Brother{
	private String name;
}

3.應(yīng)用演示類(lèi)

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);
        // 我們從克隆對(duì)象user2中修改brother,看看是否會(huì)影響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.深拷貝寫(xiě)法

這是User類(lèi)

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

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

這是Brother類(lèi)

public class Brother implements Cloneable{
    private String name;

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

這里是結(jié)果演示

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);
		// 我們從克隆對(duì)象user2中修改brother,看看是否會(huì)影響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沒(méi)有受到user2的影響,深拷貝成功!

5.圖解深拷貝與淺拷貝

在這里插入圖片描述

總結(jié)與思考

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

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

相關(guān)文章

最新評(píng)論