淺談Java設計模式之原型模式知識總結(jié)
如何使用?
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();
}
}
這里是結(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);
// 我們從克隆對象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.圖解深拷貝與淺拷貝

總結(jié)與思考
java中object類的clone()方法為淺拷貝必須實現(xiàn)Cloneable接口如果想要實現(xiàn)深拷貝,則需要重寫clone()方法
到此這篇關于淺談Java設計模式之原型模式知識總結(jié)的文章就介紹到這了,更多相關Java原型模式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot整合ZXing實現(xiàn)二維碼和條形碼的創(chuàng)建
如今我們越來越多的東西需要用到二維碼或者條形碼,商品的條形碼,付款的二維碼等等,所以本文小編給大家介紹了SpringBoot整合ZXing實現(xiàn)二維碼和條形碼的創(chuàng)建,文章通過代碼示例給大家介紹的非常詳細,需要的朋友可以參考下2023-12-12
spring mvc4的日期/數(shù)字格式化、枚舉轉(zhuǎn)換示例
本篇文章主要介紹了spring mvc4的日期/數(shù)字格式化、枚舉轉(zhuǎn)換示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下。2017-01-01
Java 使用多線程調(diào)用類的靜態(tài)方法的示例
這篇文章主要介紹了Java 使用多線程調(diào)用類的靜態(tài)方法的示例,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-10-10

