原型模式

简介

定义:这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。例如,一个对象需要在一个高代价的数据库操作之后被创建。我们可以缓存该对象,在下一个请求时返回它的克隆,在需要的时候更新数据库,以此来减少数据库调用。

使用场景:

  • 对象创建成本高

  • 需要大量相似对象

  • 避免构造函数

实现要点:

  • 实现Cloneable接口

  • 重写clone()方法

  • 浅拷贝 vs 深拷贝

代码示例

  1. 开启原型模式

@Data
public class UserPrototype implements Cloneable {
    private Integer id;
    private String name;
    private String desc;

    public UserPrototype() {
        System.out.println("创建对象成功...");
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}
  1. 使用方式

public class Test {

    public static void main(String[] args) throws CloneNotSupportedException {
        UserPrototype userPrototype = new UserPrototype();
        userPrototype.setName("本体");
        for (int i = 0; i < 10; i++) {
            UserPrototype clone = (UserPrototype) userPrototype.clone();
            System.out.println("对象创建成功---" + i + clone.getName());
        }

    }
}

Last updated

Was this helpful?