原型设计模式(Prototype)是创建型设计模式。
原型设计模式指通过已有的对象生成新的对象,我们无需知道原有的对象具体的创建细节,通常用于创建复杂的对象。
所以在重复创建相似类型的对象可以考虑使用原型模式,比如在循环体内创建对象时。
import java.util.Date; public class User implements Cloneable{ private String name; private Date birthday; public User(String name, Date birthday) { this.name = name; this.birthday = birthday; } @Override public String toString() { return "User [name=" + name + ", birthday=" + birthday + "]"; } @Override public Object clone() throws CloneNotSupportedException { return super.clone(); }
......(省略get/set)
}
测试类
public class Client { public static void main(String[] args) { try { Date birthday = new Date(1472692739L); User user01 = new User("parry", birthday); System.out.println("User01" + user01.toString()); User user02 = (User) user01.clone(); System.out.println("User02" + user02.toString()); birthday.setTime(1451577600l); System.out.println("修改birthdayUser01:" + user01.toString()); System.out.println("修改birthdayUser02:" + user02.toString()); } catch (CloneNotSupportedException e) { e.printStackTrace(); } } }
测试结果:
说明:从测试结果看,修改了birthday之后,user01和user02都发生了发生了变化;其实浅克隆对非基本数据类型是不会拷贝的,还是引用,用下面的图表示
public class User implements Cloneable{ private String name; private Date birthday; public User(String name, Date birthday) { this.name = name; this.birthday = birthday; } @Override public String toString() { return "User [name=" + name + ", birthday=" + birthday + "]"; } @Override public Object clone() throws CloneNotSupportedException { User user = (User) super.clone(); user.birthday = (Date) this.birthday.clone();//属性克隆实现深克隆 return user; } ......(省略get/set) }
测试结果:
说明:从测试结果看,修改了birthday之后,只有user01的birthday发生了变化;其实深克隆对非基本数据类型会重新克隆一份,用面的图表示:
原文:http://www.cnblogs.com/parryyang/p/5828685.html