- 原型模式应用在拷贝对象属性的场景中。很常见的操作是:在Service层产生的数据传递给Controller层的时候有大量的属性是重合的,只有个别的属性需要特别设置。我们经常用到的工具是Spring提供的工具类:
BeanUtils.copyProperties()。 - 可以基于
Object自带的clone()方法克隆对象。分为浅拷贝和深拷贝。 - 浅拷贝只拷贝属性值。
- 深拷贝会递归拷贝依赖的属性值。
- 被依赖的组件属性。
@Data @ToString public static class Component { private String name; public Component(String name) { super(); this.name = name; } @Override protected Object clone() throws CloneNotSupportedException { return new Component(getName()); } }
@Data @ToString public static class Product { private String name; private Component component; public Product(String name, Component component) { super(); this.name = name; this.component = component; } @Override protected Object clone() throws CloneNotSupportedException { // 浅拷贝,就是我们现在的一个实现 // 就是仅仅简单的对当前所有的变量进行一个拷贝// return new Product(getName(), getComponent()); // 深拷贝,递归对自己引用的对象也进行拷贝 return new Product(getName(), (Component)getComponent().clone()); } }
public static void main(String[] args) { try { Product product = new Product("测试产品", new Component("测试组件")); Product copyProduct = (Product) product.clone(); System.out.println(copyProduct); } catch (Exception e) { e.printStackTrace(); } // 原型模式,就是在要拷贝的类里实现一个clone()方法,自己拷贝自己 // 拷贝的时候,就两个概念,浅拷贝,深拷贝 // 很多地方要克隆这个对象,不要自己维护克隆的逻辑,即使克隆逻辑修改了,只要在clone()方法里面修改 }