通过new产生对象需要较为繁琐的数据准备或者权限检查,则使用原型模式。
克隆和new不同,new出的对象使用的是默认值,克隆的对象与原对象值相同且不会影响原对象的值。
public class Sheep impliments Cloneable{
private String name;
private Date birthday;
//浅克隆
@Override
protected Object clone() throws CloneNotSupportedException{
Object obj = super.clone();
return obj;
}
}
public class Sheep impliments Cloneable{
private String name;
private Date birthday;
//深克隆
@Override
protected Object clone() throws CloneNotSupportedException{
Object obj = super.clone();
Sheep sheep = (Sheep)obj;
sheep.birthday = (Date) this.birthday.clone();//属性也克隆
return obj;
}
}
深克隆还可以采用序列化
class Sheep implements Serializable{
private String name;
private Date birthday;
Sheep(String name,Date birthday){
this.name = name;
this.birthday = birthday;
}
@Override
public String toString(){
return "Sheep{"+
"name='"+name+'\''+
",birthday="+birthday+
'}';
}
}
public class Main{
public static void main(String[] args )throws Exception{
Sheep sheep = new Sheep("lomb",newDate(111));
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(sheep);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Sheep sheep1 = (Sheep)ois.readObject();
System.out.println(sheep);
System.out.println(sheep1);
System.out.println(sheep==sheep1);
}
}
结果
Sheep{name=‘lomb’, birthday=Thu Jan 01 08:00:00 CST 1970}
Sheep{name=‘lomb’, birthday=Thu Jan 01 08:00:00 CST 1970}
false