根据一个对象,创建出和原型一样的对象
1.浅克隆
public interface IPrototype {
IPrototype clone();//克隆方法
}
public class ShallowPrototype implements IPrototype {
private String name;
private int age;
private List<String> phoneList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPhoneList() {
return phoneList;
}
public void setPhoneList(List<String> phoneList) {
this.phoneList = phoneList;
}
@Override
public IPrototype clone() {
ShallowPrototype shallowPrototype = new ShallowPrototype();
shallowPrototype.setAge(this.age);
shallowPrototype.setName(this.name);
//属于引用类型,phonelist值改变两个对象的值都会改变
shallowPrototype.setPhoneList(this.phoneList);
return shallowPrototype;
}
}
2.深克隆
public class DeepPrototype implements Cloneable, Serializable {
private String name;
private int age;
private List<String> phoneList;
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<String> getPhoneList() {
return phoneList;
}
public void setPhoneList(List<String> phoneList) {
this.phoneList = phoneList;
}
public Object clone(){
return this.deepClone();
}
public DeepPrototype deepClone(){
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
DeepPrototype clone = (DeepPrototype)ois.readObject();
return clone;
}catch (Exception e){
System.out.println("深克隆异常");
e.printStackTrace();
}
return null;
}
}
使用场景:
创建一个非常复杂的对象
优点:
创建一个对象比较复杂时,使用原型对象通常效率会更高也更方便快捷
缺点
1.每个对象都需要单独实现克隆的方法。
2.深克隆和浅克隆需要灵活应用,否则可能会导致业务出错。