原型模式(Prototype pattern)
概念
克隆!拷贝!以某个对象为原型,复制出新的对象
优势
效率高(直接克隆,避免了重新执行构造过程的步骤)案例(克隆狗(需要实现Cloneable接口和clone方法))
浅克隆
创建狗类
public class DogLow implements Cloneable{
private String name; //姓名
private Date birth; //生日
public DogLow() {
}
public DogLow(String name, Date birth) {
super();
this.name = name;
this.birth = birth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
//加入clone方法
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
克隆测试
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
DogLow dog1 = new DogLow("大黄", new Date(15487888789L));
System.out.println(dog1);
System.out.println(dog1.getName());
System.out.println(dog1.getBirth());
//克隆dog2
DogLow dog2 = (DogLow)dog1.clone();
System.out.println(dog2);
System.out.println(dog2.getName());
System.out.println(dog2.getBirth());
}
}
console:
com.java.prototype.DogLow@6726a408
大黄
1970-06-29
com.java.prototype.DogLow@384f14b0
大黄
1970-06-29
深克隆(重写clone方法即可)
深克隆(采用序列化与反序列化)
/*
* 采用序列化与反序列化方式进行深克隆
*/
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(dog1);
byte[] arr = bos.toByteArray();
ByteArrayInputStream bis = new ByteArrayInputStream(arr);
ObjectInputStream ois = new ObjectInputStream(bis);
DogLow dog3 = (DogLow) ois.readObject();
System.out.println("深克隆狗3:" +dog3.getBirth());