Java设计模式之(四)——原型模式

1、什么是原型模式

Specify the kinds of objects to create using a prototypical instance,and create new objects by copying this prototype.
Prototype Design Pattern:用原型实例指定创建对象的种类, 并且通过拷贝这些原型创建新的对象。
说人话:对象复制
2、原型模式的两种实现方法
我们日常开发中,应该有使用过 BeanUtils.copyProperties()方法,其实这就是原型模式的一种用法(浅拷贝)。原型模式实现分两种:
①、浅拷贝:只会复制对象中基本数据类型数据和引用对象的内存地址,不会递归地复制引用对象,以及引用对象的引用对象
②、深拷贝:得到的是一份完完全全独立的对象。
Java 中 Object 类是所有类的根类,Object 类提供了一个 clone()方法,该方法可以将一个 Java 对象复制一份,但是在调用 clone方法的Java类必须要实现一个接口Cloneable,这是一个标志接口,标志该类能够复制且具有复制的能力,如果不实现 Cloneable 接口,直接调用clone方法,会抛出 CloneNotSupportedException 异常。
/** * A class implements the Cloneable interface to * indicate to the {@link java.lang.Object#clone()} method that it * is legal for that method to make a * field-for-field copy of instances of that class. * * Invoking Object's clone method on an instance that does not implement the * Cloneable interface results in the exception * CloneNotSupportedException being thrown. * * By convention, classes that implement this interface should override * Object.clone (which is protected) with a public method. * See {@link java.lang.Object#clone()} for details on overriding this * method. * * Note that this interface does not contain the clone method. * Therefore, it is not possible to clone an object merely by virtue of the * fact that it implements this interface.Even if the clone method is invoked * reflectively, there is no guarantee that it will succeed. * * @authorunascribed * @seejava.lang.CloneNotSupportedException * @seejava.lang.Object#clone() * @sinceJDK1.0 */ public interface Cloneable { }

关于深浅拷贝的详细说明,可以参考我的这篇博客:
https://www.cnblogs.com/ysocean/p/8482979.html
3、原型模式的优点
①、性能高
原型模式是在内存二进制流的拷贝, 要比直接new一个对象性能好很多, 特别是要在一个循环体内产生大量的对象时, 原型模式可以更好地体现其优点。
【Java设计模式之(四)——原型模式】②、避免构造函数的约束
这既是它的优点也是缺点,直接在内存中拷贝,构造函数是不会执行的 。 优点就是减少了约束, 缺点也是减少了约束, 需要大家在实际应用时考虑。
4、原型模式使用场景
①、在需要一个类的大量对象的时候,使用原型模式是最佳选择,因为原型模式是在内存中对这个对象进行拷贝,要比直接new这个对象性能要好很多,在这种情况下,需要的对象越多,原型模式体现出的优点越明显。
②、如果一个对象的初始化需要很多其他对象的数据准备或其他资源的繁琐计算,那么可以使用原型模式。
③、当需要一个对象的大量公共信息,少量字段进行个性化设置的时候,也可以使用原型模式拷贝出现有对象的副本进行加工处理。

    推荐阅读