原型模式(Prototype):用对象的类创建原型实例(对象),再通过原型实例创建新对象。多用于在保证性能的情况下,创建重复对象。
原型模式主要适用于以下场景:
1、类初始化消耗的资源相对较多。
2、new 产生的一个对象需要非常繁琐的过程(数据准备,访问权限等)。
3、构造函数比较复杂
4、循环体中生产大量的对象时。
在Spring中,原型模式应用得非常广泛。例如 scope = “prototype”,在我们经常用的JSON.parseObject()也是一种原型模式。
实现原型模式条件:1实现 Cloneable 接口;2重写 Object 类中的 clone() 方法,用于返回对象的拷贝(默认浅拷贝)
拷贝分类
拷贝类型 | 定义 |
---|---|
浅拷贝 | 如果原型对象的成员变量是值类型,将复制一份给克隆对象;如果原型对象的成员变量是引用类型,则将引用对象的地址复制一份给克隆对象,也就是说原型对象和克隆对象的成员变量指向相同的内存地址 |
深克隆 | 在深克隆中,无论原型对象的成员变量是值类型还是引用类型,都将复制一份给克隆对象,深克隆将原型对象的所有引用对象也复制一份给克隆对象。 |
使用原型模式实现深克隆实例
原型类:
public class Dag implements Serializable, Cloneable{
private String name;
private String age;
private String type;
private Dag customers;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Dag getCustomers() {
return customers;
}
public void setCustomers(Dag customers) {
this.customers = customers;
}
@Override
protected Object clone() {
ByteArrayOutputStream byteArrayOutputStream=null;
ObjectOutputStream outputStream=null;
ByteArrayInputStream byteArrayInputStream=null;
ObjectInputStream objectInputStream=null;
try {
byteArrayOutputStream=new ByteArrayOutputStream();
outputStream=new ObjectOutputStream(byteArrayOutputStream);
outputStream.writeObject(this);
byteArrayInputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream=new ObjectInputStream(byteArrayInputStream);
return objectInputStream.readObject();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}finally {
try {
byteArrayInputStream.close();
byteArrayOutputStream.close();
outputStream.close();
objectInputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
// try {
// return super.clone();
// } catch (CloneNotSupportedException e) {
// throw new RuntimeException(e);
// }
}
测试
public class test {
public static void main(String[] args) {
Dag dag = new Dag();
Dag custpmers = new Dag();
custpmers.setType("33333333");
dag.setAge("20");
dag.setName("旺财");
dag.setType("12");
dag.setCustomers(custpmers);
Dag clone = (Dag) dag.clone();
custpmers.setType("weefrerfrer");
dag.setCustomers(custpmers);
System.out.println(clone.getCustomers().getType());
}
}