文章目录
7、原型模式
**原型模式的定义:**用一个已经创建好的实例作为原型,通过复制该原型对象来创建一个和原型相同或相似的新对象。(深复制)
这种模式是实现一个接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。
**如何实现:**在Java中,就是让类继承Cloneable,重写clone方法。
public class Propoty implements Cloneable {
String name;
Date date;
public Propoty(String name, Date date) {
this.name = name;
this.date = date;
}
@Override
protected Object clone() throws CloneNotSupportedException {
Object propoty = null;
propoty = super.clone();
return propoty;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Propoty{" +
"name='" + name + '\'' +
", date=" + date +
'}';
}
public static void main(String[] args) throws CloneNotSupportedException, InterruptedException {
Date date = new Date();
Propoty propoty = new Propoty("asdf",date);
Propoty propoty2 = (Propoty) propoty.clone();
Thread.sleep(1000);
propoty2.setDate(new Date());
System.out.println(propoty);
System.out.println(propoty2); //propoto的时间与propoty2的时间不一样
}
}
使用深拷贝:(通过反序列化)
public class Hello implements Serializable {
private static final long serialVersionUID = 3L;
private String name;
private Integer age;
public Hello(String name, Integer age) {
this.name = name;
this.age = age;
}
}
public class DeepCopy implements Serializable, Cloneable {
private static final long serialVersionUID = 2L;
public Hello hello;
public String name;
@Override
protected Object clone() throws CloneNotSupportedException {
ByteArrayOutputStream bout = null;
ObjectOutputStream oout = null;
ByteArrayInputStream bin = null;
ObjectInputStream oin = null;
DeepCopy deepCopy = null;
try {
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(this);
bin = new ByteArrayInputStream(bout.toByteArray());
oin = new ObjectInputStream(bin);
deepCopy = (DeepCopy) oin.readObject();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
oin.close();
bin.close();
oout.close();
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return deepCopy;
}
public DeepCopy(Hello hello, String name) {
this.hello = hello;
this.name = name;
}
}
public class Test532 {
public static void main(String[] args) throws CloneNotSupportedException {
DeepCopy deepCopy = new DeepCopy(new Hello("sdf", 20), "ad");
DeepCopy deepCopy1 = (DeepCopy) deepCopy.clone();
System.out.println(deepCopy == deepCopy1); //false
System.out.println(deepCopy.hello == deepCopy1.hello); //false
}
}