-
原型模式(Prototype)
- 创建型
- 有一个原型
- 数据内容相同,但对象实例不同
- DTO、VO、POJO、Entity…
- DTO 和 VO 之间存在一些属性名称、类型都相同,数据库中表查询出来的对象会赋值给 DTO,MVC 中的 Model 把 DTO 中的值赋值给 VO,再把 VO 中的值传输到 View 中去
- 复制,属性名称相同、属性内容相同、属性值相同
- Spring scope=“prototype”:把对象中配置的依赖关系,在每次使用对象之前,都会创建一个新的对象,并且会将依赖关系完整的赋值给新创建的对象
- 实现方式
- 反射去实现,性能低,apache
- clone 实现,性能高
- 生活场景:孙悟空吹毫毛变猴子
/** * 浅复制 **/ public class Prototype implements Cloneable{ private String name; private final ArrayList<String> arrayList = new ArrayList<String>(); @Override public Object clone() throws CloneNotSupportedException { return super.clone(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public ArrayList<String> getArrayList() { return arrayList; } public void add(String str){ arrayList.add(str); } } public class Monkey { protected double height; protected double weight; protected Date birthday; public double getHeight() { return height; } public void setHeight(double height) { this.height = height; } public double getWeight() { return weight; } public void setWeight(double weight) { this.weight = weight; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } } public class JinGuBang implements Serializable { private double height = 100; private double diameter = 10; public void big() { this.diameter *= 2; this.height *= 2; } public void small() { this.diameter /= 2; this.height /= 2; } } /** * 深复制 */ public class WuKong extends Monkey implements Cloneable,Serializable { private final JinGuBang jinGuBang = new JinGuBang(); public WuKong(){ this.birthday = new Date(); } public JinGuBang getJinGuBang() { return jinGuBang; } @Override public Object clone() throws CloneNotSupportedException { super.clone(); return this.deepClone(); } private Object deepClone(){ try { final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); final ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(this); final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); final ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); return objectInputStream.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); return null; } } }