淺談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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
如何用idea編寫并運行第一個spark scala處理程序
詳細介紹了如何使用IntelliJ IDEA創(chuàng)建Scala項目,包括配置JDK和Scala SDK,添加Maven支持,編輯pom.xml,并創(chuàng)建及運行Scala程序,這為Scala初學者提供了一個基礎的項目搭建和運行指南2024-09-09一文搞懂并學會使用SpringBoot的Actuator運行狀態(tài)監(jiān)控組件的詳細教程
這篇文章主要介紹了一文搞懂并學會使用SpringBoot的Actuator運行狀態(tài)監(jiān)控組件,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09Spring Boot ActiveMQ發(fā)布/訂閱消息模式原理解析
這篇文章主要介紹了Spring Boot ActiveMQ發(fā)布/訂閱消息模式原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07Hibernate 與 Mybatis 的共存問題,打破你的認知!(兩個ORM框架)
這篇文章主要介紹了Hibernate 與 Mybatis 如何共存?本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08