原型模式 Prototype

发布时间 2023-12-21 08:54:44作者: 梅丹隆

一、定义

指原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象

二、特点

  • 不需要知道任何创建细节,不调用构造函数
  • 实现Clonable接口

三、适用场景

  1. 累出实话消耗资源较多
  2. new产生一个对象需要非常繁琐的过程(如:数据准备、访问权限等)
  3. 构造函数比较复杂
  4. 循环体中产生大量对象时

四、优缺点

1、优点

  1. 原型模式性能比直接new一个对象高
  2. 简化对象创建过程

2、缺点

  1. 必须配备克隆方法
  2. 对克隆复杂对象,或对克隆出的对象进行复杂改造时,容易引入风险
  3. 深拷贝、浅拷贝运用需得当

五、代码实现

https://github.com/Meidanlong/all-in-one/tree/master/design/src/main/java/com/mdl/design/pattern/creational/prototype

public class Pig implements Cloneable{
    private String name;
    private Date birthday;

    public Pig(String name, Date birthday) {
        this.name = name;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Pig pig = (Pig)super.clone();

        //深克隆
        pig.birthday = (Date) pig.birthday.clone();
        return pig;
    }

    @Override
    public String toString() {
        return "Pig{" +
                "name='" + name + '\'' +
                ", birthday=" + birthday +
                '}'+super.toString();
    }
}