概念
原型模式属于创建型模式,它提供了一种创建对象的最佳方式。是用于创建重复的对象,同时又能保证性能。指定创建对象的种类,通过拷贝复制这些原型,创建新的对象。当直接创建对象的代价比较大时,则采用这种模式。
UML
拷贝方式
浅拷贝
@Data
@AllArgsConstructor
public class Parent {
private String name;
}
@Data
@AllArgsConstructor
public class Sleep1 implements Cloneable {
private String name;
private int age;
private String color;
//Parent 无需实现Cloneable 进行拷贝
private Parent parent;
@Override
protected Sleep1 clone() {
Sleep1 sleep=null;
try {
sleep = (Sleep1) super.clone();
} catch (CloneNotSupportedException e) {
System.out.println("clone失败");
}
return sleep;
}
}
- 浅拷贝无法将属性中为对象的类型加以拷贝,而是保存一份链接指向对应对象
深拷贝
- 深拷贝则与浅拷贝相反,能将所有对象已经属性对象都拷贝一份
通过实现cloneable接口拷贝
- 缺点是所有引用的对象都需要实现拷贝,无限套娃,对类改动较大
@Data
@AllArgsConstructor
public class Child implements Cloneable {
private String name;
@Override
public Child clone() throws CloneNotSupportedException {
return (Child)super.clone();
}
}
@Data
@AllArgsConstructor
public class Sleep2 implements Cloneable {
private String name;
private int age;
private String color;
private Child child;
//深拷贝
@Override
protected Sleep2 clone() {
Sleep2 sleep=null;
try {
sleep = (Sleep2) super.clone();
sleep.child=child.clone();
} catch (CloneNotSupportedException e) {
System.out.println("clone失败");
}
return sleep;
}
}
通过序列化来拷贝
@Data
@AllArgsConstructor
public class Sleep3 implements Serializable {
private String name;
private int age;
private String color;
private Parent parent;
public Sleep3 depepClone() {
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try{
//序列化
bos=new ByteArrayOutputStream();
oos=new ObjectOutputStream(bos);
//将当前对象以流方式输出
oos.writeObject(this);
//反序列化
bis=new ByteArrayInputStream(bos.toByteArray());
ois=new ObjectInputStream(bis);
Sleep3 sleep3=(Sleep3) ois.readObject();
return sleep3;
}catch (Exception e){
System.out.println("反列化失败");
return null;
}finally {
try {
bos.close();
oos.close();
bis.close();
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}