介绍
* 原型模式:
* 在运行期间, 根据原型实例动态创建出一个新实例;
* 应用场景:
* 克隆一个完全独立对象; (深克隆)
* 创建一个对象需要高代价时;
* 比如需要大量查询数据库, 可缓存该对象二进制数据, 使用时读取对象; (深克隆)
* 多次使用同一个对象:
* 在spring中配置bean为非单例时, 每次获取bean都采用原型模式创建对象;
* JSONObject obj = JSON.parseObject(String jsonStr): 根据json字符串原型, 创建JSONObject
* 原型模式和单例模式是冲突的;
代码
思路
* 原型模式的实现有以下方式:
1. 人工根据对象创建出另外一个对象;
* 可深可浅
2. 实现Cloneable, 使用clone()方法克隆:
* 浅克隆
3. 使用序列化Serializeable克隆:
* 深克隆;
* 注意: 对象中的引用数据类型及其父类必须实现Serializeable, 才能被深克隆;
代码
public class ModlePrototype implements Cloneable, Serializable{
private String name;
private int age;
private List<String> hobby;
//人工克隆
public ModlePrototype clone(ModlePrototype target){
ModlePrototype modle = new ModlePrototype();
modle.setAge(target.getAge());
modle.setName(target.getName());
modle.setHobby(target.getHobby()); //浅克隆
return modle;
}
//cloneable 浅克隆
public ModlePrototype cloneV2() throws Exception{
return (ModlePrototype) this.clone();
}
//深克隆; 引用数据类型(包括父类)必须实现Serializeable才能被深克隆;
public ModlePrototype cloneV3(ModlePrototype target) throws Exception{
String filename = "d:\\abc";
FileOutputStream fos = new FileOutputStream(filename);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(target);
oos.flush();
oos.close();
FileInputStream fis = new FileInputStream(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
ModlePrototype modle = (ModlePrototype) ois.readObject();
ois.close();
return modle;
}
public List<String> getHobby() {
return hobby;
}
public void setHobby(List<String> hobby) {
this.hobby = hobby;
}
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;
}
}