找回密码
 立即注册
首页 业界区 安全 09.创建型 - 原型模式 (Prototype Pattern)

09.创建型 - 原型模式 (Prototype Pattern)

蒲善思 2025-11-24 22:55:03
原型模式 (Prototype Pattern)

原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。
创建/复用大量的对象, 且对象的创建过程较复杂, 内部有复杂的依赖 部分可以共用或者不共用.  可以将创建/克隆的过程委托实例对象本身进行操作.
浅克隆
  1. @Data  
  2. public class PrototypePattern implements Cloneable {  
  3.         String baseString;  
  4.         Person refPerson;  
  5.        
  6.         @Override  
  7.         protected Object clone() throws CloneNotSupportedException {  
  8.                 return super.clone();  
  9.         }
  10.         @Data  
  11.         static class Person{  
  12.                 String name;  
  13.         }  
  14.           
  15.         public static void main(String[] args) throws CloneNotSupportedException {  
  16.                 PrototypePattern o1 = new PrototypePattern();  
  17.                 o1.baseString = "test";  
  18.                 o1.refPerson = new Person();  
  19.                 PrototypePattern o2 = (PrototypePattern) o1.clone();  
  20.                 System.out.println("浅克隆 o1 == o2: "+ (o1 == o2) );  
  21.                 System.out.println("浅克隆 o1.baseString == o2.baseString: "+ (o1.baseString == o2.baseString) );  
  22.                 System.out.println("浅克隆 o1.refPerson == o2.refPerson: "+ (o1.refPerson == o2.refPerson) );
  23.                 /**
  24.                 浅克隆 o1 == o2: false
  25.                 浅克隆 o1.baseString == o2.baseString: true
  26.                 浅克隆 o1.refPerson == o2.refPerson: true
  27.                 **/
  28.           
  29.         }  
  30.           
  31. }
复制代码
对于引用类型:
clone 方法是浅拷贝,对象内属性引用的对象只会拷贝引用地址,而不会将引用的对象重新分配内存
对于基本类型:
基本数据类型在赋值的时候,永远都是传值,而不是传引用
  1. double m = 4; // 此时, 给变量m,开辟了8bytes的内存空间存储
  2. double n = m; // 此时也会,给变量n,开辟新的8bytes内存空间
复制代码
基于Java的 Object::clone() 方法: JVM会进行内存操作直接 二进制拷贝原始数据流, 简单粗暴, 不会有其他更多的复杂操作(调用构造,初始化等等), 速度远远快于实例化操作;
Creates and returns a copy of this object. The precise meaning of "copy" may depend on the class of the object.
The general intent is that, for any object x, the expression:
x.clone() != xwill be true, and that the expression: x.clone().getClass() == x.getClass()will be true
but these are not absolute requirements. While it is typically the case that:
x.clone().equals(x) will be true, this is not an absolute requirement.
java.lang.Object#clone
  1. /**
  2.      * Creates and returns a copy of this object.  The precise meaning
  3.      * of "copy" may depend on the class of the object. The general
  4.      * intent is that, for any object {@code x}, the expression:
  5.      * <blockquote>
  6.      * <pre>
  7.      * x.clone() != x</pre></blockquote>
  8.      * will be true, and that the expression:
  9.      * <blockquote>
  10.      * <pre>
  11.      * x.clone().getClass() == x.getClass()</pre></blockquote>
  12.      * will be {@code true}, but these are not absolute requirements.
  13.      * While it is typically the case that:
  14.      * <blockquote>
  15.      * <pre>
  16.      * x.clone().equals(x)</pre></blockquote>
  17.      * will be {@code true}, this is not an absolute requirement.
  18.      * <p>
  19.      * By convention, the returned object should be obtained by calling
  20.      * {@code super.clone}.  If a class and all of its superclasses (except
  21.      * {@code Object}) obey this convention, it will be the case that
  22.      * {@code x.clone().getClass() == x.getClass()}.
  23.      * <p>
  24.      * By convention, the object returned by this method should be independent
  25.      * of this object (which is being cloned).  To achieve this independence,
  26.      * it may be necessary to modify one or more fields of the object returned
  27.      * by {@code super.clone} before returning it.  Typically, this means
  28.      * copying any mutable objects that comprise the internal "deep structure"
  29.      * of the object being cloned and replacing the references to these
  30.      * objects with references to the copies.  If a class contains only
  31.      * primitive fields or references to immutable objects, then it is usually
  32.      * the case that no fields in the object returned by {@code super.clone}
  33.      * need to be modified.
  34.      *
  35.      * @implSpec
  36.      * The method {@code clone} for class {@code Object} performs a
  37.      * specific cloning operation. First, if the class of this object does
  38.      * not implement the interface {@code Cloneable}, then a
  39.      * {@code CloneNotSupportedException} is thrown. Note that all arrays
  40.      * are considered to implement the interface {@code Cloneable} and that
  41.      * the return type of the {@code clone} method of an array type {@code T[]}
  42.      * is {@code T[]} where T is any reference or primitive type.
  43.      * Otherwise, this method creates a new instance of the class of this
  44.      * object and initializes all its fields with exactly the contents of
  45.      * the corresponding fields of this object, as if by assignment; the
  46.      * contents of the fields are not themselves cloned. Thus, this method
  47.      * performs a "shallow copy" of this object, not a "deep copy" operation.
  48.      * <p>
  49.      * The class {@code Object} does not itself implement the interface
  50.      * {@code Cloneable}, so calling the {@code clone} method on an object
  51.      * whose class is {@code Object} will result in throwing an
  52.      * exception at run time.
  53.      *
  54.      * @return     a clone of this instance.
  55.      * @throws  CloneNotSupportedException  if the object's class does not
  56.      *               support the {@code Cloneable} interface. Subclasses
  57.      *               that override the {@code clone} method can also
  58.      *               throw this exception to indicate that an instance cannot
  59.      *               be cloned.
  60.      * @see java.lang.Cloneable
  61.      */
  62.     @IntrinsicCandidate
  63.     protected native Object clone() throws CloneNotSupportedException;
复制代码
Java Cloneable 接口的作用


  • Cloneable接口是标记型接口,内部没有方法和属性
  • 实现 Cloneable 接口来表示该类可以被克隆,才可以调用Object.clone() 方法对该类的实例进行按字段复制。
  • 如果在没有实现Cloneable 接口的实例上调用Object.clone() 方法,则会抛出 CloneNotSupportedException 异常。
深克隆 基于序列化
  1. @Data
  2. public class PrototypePattern implements Cloneable, Serializable {
  3.     String baseString;
  4.     Person refPerson;
  5.     @Data
  6.     static class Person implements Serializable{
  7.         String name;
  8.     }
  9.     public static void main(String[] args) throws Exception {
  10.         PrototypePattern o1 = new PrototypePattern();
  11.         o1.baseString = "test";
  12.         o1.refPerson = new Person();
  13.         //创建对象序列化输出流
  14.         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("o1.data"));
  15.         //将o1对象写到文件中
  16.         oos.writeObject(o1);
  17.         oos.close();
  18.         //创建对象序列化输入流
  19.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("o1.data"));
  20.         //读取对象
  21.         PrototypePattern o2 = (PrototypePattern) ois.readObject();
  22.         System.out.println("深克隆 o1 == o2: "+ (o1 == o2) );
  23.         System.out.println("深克隆 o1.baseString == o2.baseString: "+ (o1.baseString == o2.baseString) );
  24.         System.out.println("深克隆 o1.refPerson == o2.refPerson: "+ (o1.refPerson == o2.refPerson) );
  25.         /**
  26.                 深克隆 o1 == o2: false
  27.                 深克隆 o1.baseString == o2.baseString: false
  28.                 深克隆 o1.refPerson == o2.refPerson: false
  29.         **/
  30.     }
  31. }
复制代码
Java Serializable 接口的作用


  • Serializable 接口是标记型接口,内部没有方法和属性
  • ObjectOutPutStream 在序列化的时候,会判断对象的类型,如果不是字符串、数组、枚举、Serializable 的实例,会抛出 NotSerializableException
原型模式总结

原型模式优缺点

原型模式优点

  • 当创建新的对象实例较为复杂时,使用原型模式可以简化对象的创建过程, 通过复制一个已有实例可以提高新实例的创建效率.
    比如,在 AI 系统中,我们经常需要频繁使用大量不同分类的数据模型文件,在对这一类文件建立对象模型时,不仅会长时间占用 IO 读写资源,还会消耗大量 CPU 运算资源,如果频繁创建模型对象,就会很容易造成服务器 CPU 被打满而导致系统宕机。
    通过原型模式我们可以很容易地解决这个问题,当我们完成对象的第一次初始化后,新创建的对象便使用对象拷贝(在内存中进行二进制流的拷贝),虽然拷贝也会消耗一定资源,但是相比初始化的外部读写和运算来说,内存拷贝消耗会小很多,而且速度快很多

  • 原型模式提供了简化的创建结构,工厂方法模式常常需要有一个与产品类等级结构相同的工厂等级结构(具体工厂对应具体产品),而原型模式就不需要这样,原型模式的产品复制是通过封装在原型类中的克隆方法实现的,无须专门的工厂类来创建产品.
  • 可以使用深克隆的方式保存对象状态,使用原型模式将对象复制一份并将其状态保存起来,以便在需要的时候使用,比如恢复到某一历史状态,可以辅助实现撤销操作.
    在某些需要保存历史状态的场景中,比如,聊天消息、上线发布流程、需要撤销操作的程序等,原型模式能快速地复制现有对象的状态并留存副本,方便快速地回滚到上一次保存或最初的状态,避免因网络延迟、误操作等原因而造成数据的不可恢复。

原型模式缺点

  • 需要为每一个类配备一个克隆方法, 而且该克隆方法位于一个类的内部,当对已有的类进行改造时需要修改源代码, 违背了开闭原则.
使用场景

原型模式常见的使用场景有以下六种。

  • 资源优化场景。也就是当进行对象初始化需要使用很多外部资源时,比如,IO 资源、数据文件、CPU、网络和内存等。(比如游戏可复用的资源对象, 地图块, 背景,  只有部分(方向,颜色)属性不一样 )
  • 复杂的依赖场景。 比如,F 对象的创建依赖 A,A 又依赖 B,B 又依赖 C……于是创建过程是一连串对象的 get 和 set。
  • 性能和安全要求的场景。 比如,同一个用户在一个会话周期里,可能会反复登录平台或使用某些受限的功能,每一次访问请求都会访问授权服务器进行授权,但如果每次都通过 new 产生一个对象会非常烦琐,这时则可以使用原型模式。
  • 同一个对象可能被多个修改者使用的场景。 比如,一个商品对象需要提供给物流、会员、订单等多个服务访问,而且各个调用者可能都需要修改其值时,就可以考虑使用原型模式。
  • 需要保存原始对象状态的场景。 比如,记录历史操作的场景中,就可以通过原型模式快速保存记录。


来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册