设计模式--原型模式及其编程思想

种地  金牌会员 | 2024-11-27 21:37:41 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 928|帖子 928|积分 2784

原型模式(Prototype Pattern)

原型模式的核心思想是通过复制(克隆)现有对象来创建新对象
原型模式通常涉及两个角色:原型对象和具体原型对象。原型对象是需要被复制的对象,而具体原型对象是实现了克隆方法的原型对象。
在Java中,原型模式通常通过实现Cloneable接口和重写clone()方法来实现。当需要创建新对象时,可以直接调用原型对象的clone()方法来得到一个新的对象副本,而无需调用构造函数大概暴露对象创建的具体细节。
原型模式在一些场景中非常有用,例如:

  • 简化对象创建:在对象的构造过程比较复杂或时,使用原型模式可以很容易地复制整个对象结构,而不需要关心对象的具体构成和组装方式。
  • 隐藏具体实现:客户端可以针对抽象接口进行编程,而不需要知道具体的实现细节。
  • 通过为每个线程创建 独立的对象实例 ,来避免差别线程对该对象的操作可能会产生数据冲突大概不一致。
  • 在某些情况下,对象的创建过程可能是受限的,而原型模式可以绕过这些限定。
简单案例

案例概述
简单实现原型模式,观察原型创建的对象是不是同一个对象,内容是否雷同
  1. // 原型对象和具体原型对象
  2. public class ConcretePrototype implements Cloneable {
  3.     private String name;

  4.     public ConcretePrototype(String name) {
  5.         this.name = name;
  6.     }

  7.     public String getName() {
  8.         return name;
  9.     }

  10.     @Override
  11.     public ConcretePrototype clone() {
  12.         try {
  13.             return (ConcretePrototype) super.clone();
  14.         } catch (CloneNotSupportedException e) {
  15.             e.printStackTrace();
  16.             return null;
  17.         }
  18.     }

  19. }

  20. // 测试代码
  21. class PrototypePatternDemo {
  22.     public static void main(String[] args) {
  23.         ConcretePrototype original = new ConcretePrototype("Prototype1");
  24.         // 克隆出新对象
  25.         ConcretePrototype cloned = original.clone();
  26.         // 观察输出的地址和内容
  27.         System.out.println(original+"|"+"Original: " + original.getName());
  28.         System.out.println(cloned+"|"+"Cloned: " + cloned.getName());
  29.     }
  30. }
复制代码
测试结果:

上面的简单案例是属于原型模式中的浅拷贝,除此之外原型模式另有深拷贝。
浅拷贝

浅拷贝:创建的新对象和原始对象的基本数据类型属性会被直接复制,而对于引用类型的属性,原始对象和克隆对象会共享雷同的引用。所以,如果克隆对象和原始对象共享了某些引用类型的属性,对此中一个对象的修改会影响到另一个对象。
浅拷贝示例
  1. public class ShallowCopy {

  2.     public static void main(String[] args) throws CloneNotSupportedException {
  3.         Address addr = new Address("New York");
  4.         Person p1 = new Person("John", 25, addr);
  5.         System.out.println("复制修改前--地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // John - New York

  6.         Person p2 = (Person) p1.clone();
  7.         p2.name = "Denny";
  8.         p2.address.city = "Los Angeles";  // 修改了引用类型的属性
  9.         // 引用对象的值被修改后原始对象的值也发生了改变
  10.         System.out.println("原始对象地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // John - Los Angeles
  11.         System.out.println("复制对象地址:"+ p2 + "|" + p2.name + " - " + p2.address.city); // Denny - Los Angeles
  12.     }
  13. }

  14. class Person implements Cloneable {
  15.     String name;
  16.     int age;
  17.     Address address; // 引用类型

  18.     public Person(String name, int age, Address address) {
  19.         this.name = name;
  20.         this.age = age;
  21.         this.address = address;
  22.     }

  23.     @Override
  24.     protected Object clone() throws CloneNotSupportedException {
  25.         return super.clone(); // 浅拷贝
  26.     }
  27. }

  28. class Address {
  29.     String city;

  30.     public Address(String city) {
  31.         this.city = city;
  32.     }
  33. }
复制代码
测试结果:
在这个例子中,p1 和 p2 是两个差别的 Person 对象,但是它们共享同一个 Address 对象的引用。修改 p2 的 address 属性时,也会影响到 p1。

深拷贝

深拷贝:创建的新对象不光会复制原对象的基本数据类型属性,还会递归地复制对象中全部引用类型的属性。深拷贝确保原始对象和克隆对象之间完全独立,修改一个对象不会影响另一个对象。
深拷贝方式1--一个个手动克隆

对应字段为引用对象的进行一个个实例化新对象并拷贝对象数据,大概层层往下clone()。适用于,引用对象少的情况。
  1. public class DeepCopy {
  2.     public static void main(String[] args) throws CloneNotSupportedException {
  3.         Address addr = new Address("New York");
  4.         Person p1 = new Person("John", 25, addr);
  5.         System.out.println("复制修改前--地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // John - New York

  6.         Person p2 = (Person) p1.clone();
  7.         p2.name = "Denny";
  8.         p2.address.city = "Los Angeles";  // 修改了引用类型的属性
  9.         // 引用对象的值被修改后原始对象的值--不受影响
  10.         System.out.println("原始对象地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // John - Los Angeles
  11.         System.out.println("复制对象地址:"+ p2 + "|" + p2.name + " - " + p2.address.city); // Denny - Los Angeles
  12.     }
  13. }
  14. class Person implements Cloneable {
  15.     String name;
  16.     int age;
  17.     Address address; // 引用类型

  18.     public Person(String name, int age, Address address) {
  19.         this.name = name;
  20.         this.age = age;
  21.         this.address = address;
  22.     }

  23.     @Override
  24.     protected Object clone() throws CloneNotSupportedException {
  25.         Person cloned = (Person) super.clone();
  26.         cloned.address = new Address(this.address.city); // 手动克隆引用类型的属性
  27.         return cloned;
  28.     }
  29. }

  30. class Address {
  31.     String city;

  32.     public Address(String city) {
  33.         this.city = city;
  34.     }
  35. }
复制代码
测试结果:
在这个例子中,p1 和 p2 是两个独立的 Person 对象,且它们的 address 属性是独立的。修改 p2 的 address 不会影响 p1。

深拷贝方式2--序列化

序列化是将对象转换为字节流的过程,而反序列化则是将字节流转换回对象。通过序列化和反序列化,可以实现在不依赖于类构造器的情况下创建一个完全独立的对象副本。这种方式适用于对象较为复杂且具有多个引用的情况。
  1. package org.example.prototype;

  2. import java.io.*;

  3. public class DeepCopySerial {

  4.     public static void main(String[] args) {
  5.         Address addr = new Address("New York");
  6.         Person p1 = new Person("Jack", 25, addr);
  7.         System.out.println("原始对象地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // Jack - New York

  8.         // 使用深拷贝方法复制对象
  9.         Person p2 = p1.deepClone();
  10.         p2.name = "Denny";
  11.         p2.address.city = "Los Angeles";  // 修改引用类型的属性

  12.         // 打印两个对象的状态
  13.         System.out.println("原始对象地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // Jack - New York
  14.         System.out.println("复制对象地址:"+ p2 + "|" + p2.name + " - " + p2.address.city); // Denny - Los Angeles
  15.     }
  16. }

  17. class Address implements Serializable {
  18.     String city;

  19.     public Address(String city) {
  20.         this.city = city;
  21.     }
  22. }

  23. class Person implements Serializable {
  24.     String name;
  25.     int age;
  26.     Address address;

  27.     public Person(String name, int age, Address address) {
  28.         this.name = name;
  29.         this.age = age;
  30.         this.address = address;
  31.     }

  32.     // 序列化深拷贝方法
  33.     public Person deepClone() {
  34.         try {
  35.             // 将当前对象序列化到字节数组流
  36.             ByteArrayOutputStream byteOutStream = new ByteArrayOutputStream();
  37.             ObjectOutputStream out = new ObjectOutputStream(byteOutStream);
  38.             out.writeObject(this);

  39.             // 从字节数组流反序列化为新对象
  40.             ByteArrayInputStream byteInStream = new ByteArrayInputStream(byteOutStream.toByteArray());
  41.             ObjectInputStream in = new ObjectInputStream(byteInStream);
  42.             return (Person) in.readObject();
  43.         } catch (IOException | ClassNotFoundException e) {
  44.             e.printStackTrace();
  45.             return null;
  46.         }
  47.     }
  48. }
复制代码
测试结果:

优点:

  • 简便和通用:无论对象的深度如何复杂,序列化和反序列化都可以精确地复制对象。
  • 无需手动处理每个字段:不需要像手动实现深拷贝那样去关心对象的字段及其引用关系。
缺点:

  • 性能开销:序列化和反序列化过程相对较慢,尤其是对于大型对象。
  • 依赖Serializable:对象必须实现 Serializable 接口,如果类没有实现这个接口,无法进行序列化。
深拷贝方式3--第三方库

使用第三方库进行拷贝,比如Apache Commons Lang 提供了 SerializationUtils.clone() 方法,这个方法通过序列化来实现深拷贝,使用起来非常简便。
  1. import org.apache.commons.lang3.SerializationUtils;
  2. import java.io.Serializable;

  3. public class DeepCopyWithLibrary {
  4.     public static void main(String[] args) {
  5.         Address addr = new Address("New York");
  6.         Person p1 = new Person("Jack", 25, addr);
  7.         System.out.println("原始对象地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // Jack - New York

  8.         // 使用 Apache Commons 库进行深拷贝
  9.         Person p2 = SerializationUtils.clone(p1);

  10.         p2.name = "Denny";
  11.         p2.address.city = "Los Angeles";  // 修改引用类型的属性

  12.         // 打印两个对象的状态
  13.         System.out.println("原始对象地址:"+ p1 + "|" + p1.name + " - " + p1.address.city); // Jack - New York
  14.         System.out.println("复制对象地址:"+ p2 + "|" + p2.name + " - " + p2.address.city); // Denny - Los Angeles
  15.     }
  16. }


  17. class Address implements Serializable {
  18.     String city;

  19.     public Address(String city) {
  20.         this.city = city;
  21.     }
  22. }

  23. class Person implements Serializable {
  24.     String name;
  25.     int age;
  26.     Address address;

  27.     public Person(String name, int age, Address address) {
  28.         this.name = name;
  29.         this.age = age;
  30.         this.address = address;
  31.     }
  32. }
复制代码
测试结果和序列化雷同。
看看JDK源码怎么写的

java.util.Calendar类的拷贝源码,这里说的就是对应方式1,一个个手动克隆,通过new的方式和层层调用clone()方法other.zone = (TimeZone) zone.clone();来实现。
[code]public Object clone()
    {
        try {
            Calendar other = (Calendar) super.clone();

            other.fields = new int[FIELD_COUNT];
            other.isSet = new boolean[FIELD_COUNT];
            other.stamp = new int[FIELD_COUNT];
            for (int i = 0; i 

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

种地

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表