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

如何使用?

1.首先定義一個User類,它必須實現瞭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()方法為淺拷貝必須實現Cloneable接口如果想要實現深拷貝,則需要重寫clone()方法

到此這篇關於淺談Java設計模式之原型模式知識總結的文章就介紹到這瞭,更多相關Java原型模式內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: