原型模式
用一个已经创建的实例作为原型,通过克隆 获得一个新对象
使用场景
- 类的初始化消耗资源过多
- new产生的一个对象需要非常繁琐的过程
- 循环体中生产大量对象时,可读性下降
- 构造函数比较复杂
浅克隆
适用场景
克隆出来的对象和原对象中的 属性地址 一样
public class Prototype implements Cloneable {
private int age;
private List hobbies;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List getHobbies() {
return hobbies;
}
public void setHobbies(List hobbies) {
this.hobbies = hobbies;
}
@Override
protected Prototype clone() throws CloneNotSupportedException {
Prototype prototype = new Prototype();
prototype.setAge(this.age);
prototype.setHobbies(this.hobbies);
return prototype;
}
}
深克隆
适用场景
克隆出一个全新的对象
public class Prototype implements Cloneable, Serializable {
private int age;
private List hobbies;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List getHobbies() {
return hobbies;
}
public void setHobbies(List hobbies) {
this.hobbies = hobbies;
}
@Override
protected Prototype clone() throws CloneNotSupportedException {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
oos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Prototype prototype = (Prototype) ois.readObject();
return prototype;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}