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