原型模式是指原型实例指定创建对象的种类,并且通过复制这些原型对象创建新的对象
原型模式主要适用于以下场景
1.类初始化消耗资源比较多
2.使用new生成一个对象是一个比较繁琐的过程(数据准备,访问权限)
3.构造函数比较复杂
4.在循环体中产生大量对象
1.浅克隆
首先创建原型Prototype接口
public interface Prototype {
Prototype clone();
}
创建具体需要克隆的类
public class ConcretePrototype implements Prototype {
private String name;
private int age;
private List hobbies;
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 getHobbies() {
return hobbies;
}
public void setHobbies(List hobbies) {
this.hobbies = hobbies;
}
@Override
public Prototype clone() {
ConcretePrototype con = new ConcretePrototype();
con.setAge(this.age);
con.setName(this.name);
con.setHobbies(this.hobbies);
return con;
}
}
创建Client类
public class Client {
private Prototype prototype;
public Client(Prototype prototype) {
this.prototype = prototype;
}
public Prototype startClone(Prototype con) {
return con.clone();
}
}
浅克隆只是完整复制了值类型数据,没有赋值引用对象。换而言之所有引用对象仍然指向原来的对象
2.深克隆
public Object 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);
QiTianDaSheng copy = (QiTianDaSheng) ois.readObject();
copy.birthday = new Date();
return copy;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
3.克隆破坏单例模式
如果我们克隆的目标对象是单例对象,那么意味着深克隆会破坏单例模式。实际上为了防止克隆破坏单例的思路很简单,禁止深克隆即可,要么我们的单例类不实现Cloneable接口,要么我们重写clone()方法,在clone()方法中返回单例对象