package designpattern.prototype; public class Singer implements Cloneable { String name; int age; HotMusic hotMusic; public Singer(String name, int age, HotMusic hotMusic) { super(); this.name = name; this.age = age; this.hotMusic = hotMusic; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public HotMusic getHotMusic() { return hotMusic; } public void setHotMusic(HotMusic hotMusic) { this.hotMusic = hotMusic; } @Override protected Object clone() throws CloneNotSupportedException { Singer singerClone = (Singer) super.clone(); singerClone.hotMusic = (HotMusic) hotMusic.clone();// 这一句,下面解释 return singerClone; } @Override public String toString() { return "Singer [name=" + name + ", age=" + age + ", hotMusic=" + hotMusic + "]"; } }
package designpattern.prototype; public class HotMusic implements Cloneable { String name; String date; public HotMusic(String name, String date) { super(); this.name = name; this.date = date; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } @Override public String toString() { return "HotMusic [name=" + name + ", date=" + date + "]"; } }
package designpattern.prototype; public class Client { public static void main(String[] args) { Singer singer1 = new Singer("周杰伦", 40, new HotMusic("告白气球", "2016")); System.out.println(singer1); try { Singer singer2 = (Singer) singer1.clone(); singer2.hotMusic.setName("等你下课"); singer2.hotMusic.setDate("2018"); System.out.println("========================================================"); System.out.println(singer1); System.out.println(singer2); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
Singer [name=周杰伦, age=40, hotMusic=HotMusic [name=告白气球, date=2016]] ======================================================== Singer [name=周杰伦, age=40, hotMusic=HotMusic [name=告白气球, date=2016]] Singer [name=周杰伦, age=40, hotMusic=HotMusic [name=等你下课, date=2018]]
Singer [name=周杰伦, age=40, hotMusic=HotMusic [name=告白气球, date=2016]] ======================================================== Singer [name=周杰伦, age=40, hotMusic=HotMusic [name=等你下课, date=2018]] Singer [name=周杰伦, age=40, hotMusic=HotMusic [name=等你下课, date=2018]]
原文:https://www.cnblogs.com/imoqian/p/10680241.html