定义
原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象,调用者不需要知道任何创建细节,不调用构造函数
适用场景
1.类初始化消耗资源多
2.new产生的一个对象需要非常繁琐的过程(数据准备,访问权限等)
3.构造函数比较复杂
4.循环中生产大量对象时
优点
- 性能优良,Java自带,原型模式是基于内存二进制流的拷贝,比直接new对象性能提升很多
2.可以使用深克隆方式保存对象的状态,使用原型模式将对象复制一份并将其状态保存起来,简化创建过程
缺点
1.必须配备克隆(或可拷贝)方法
2.当对已有类进行改造的时候,需要修改代码,违反了开闭原则
3.深浅拷贝需运用得当
浅克隆(拷贝引用)
public class member implements Cloneable,Serializable{
private String name;
private Integer age;
private ArrayList<String> hobbiesList;
@Override
protected member clone() {
try {
return (member) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
return null;
}
}
}
存在的问题
浅克隆会改变被克隆对象引用类型的值,因为克隆时是直接将被克隆对象的引用地址复制,并未克隆具体值
深克隆(拷贝值)
protected member deepClone(){
ByteArrayOutputStream byteArrayOutputStream = null;
ObjectOutputStream objectOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
ObjectInputStream objectInputStream = null;
try {
byteArrayOutputStream = new ByteArrayOutputStream();
objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(this);
byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
objectInputStream = new ObjectInputStream(byteArrayInputStream);
return (member) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (objectInputStream != null) {
byteArrayOutputStream.close();
}
if (objectOutputStream != null) {
objectOutputStream.close();
}
if (byteArrayInputStream != null) {
byteArrayInputStream.close();
}
if (objectInputStream != null) {
objectInputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
除了使用序列化、反序列化,还可以通过转JSON创建
原型模式与单例模式是冲突的,二者不同时出现