Skip to content

Latest commit

 

History

History
98 lines (51 loc) · 1.4 KB

原型模式.md

File metadata and controls

98 lines (51 loc) · 1.4 KB

原型模式

目的

  • 使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象

类图

角色

  • Client : 调用类
  • Prototype : 抽象原型类
  • ConcretePrototype:具体实现类

1592361557889

实现

原型类

public abstract class Prototype {
    abstract Prototype clone();
}

实现类

public class ConcretePrototype extends Prototype {

    private String filed;

    public ConcretePrototype(String filed) {
        this.filed = filed;
    }

    @Override
    Prototype clone() {
        return new ConcretePrototype(filed);
    }

    @Override
    public String toString() {
        return filed;
    }
}

调用类

public class Client {
    public static void main(String[] args) {
        Prototype prototype = new ConcretePrototype("abc");
        Prototype clone = prototype.clone();
        ...
    }
}

优缺点

优点

  • 隐藏了对象创建的细节,大大提升了性能。
  • 不用重新初始化对象,而是动态的获得对象运行时的状态。

缺点

深复制 or 浅复制 。

使用场景

在初始化信息不发生变化的情况下,或者需要重复创建相似对象时可以考虑使用。比如 JDK 中的 Date 类。