Java 原型模式 详解

[复制链接]
发表于 2025-10-1 22:36:42 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

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

×
原型模式详解

一、原型模式概述

原型模式(Prototype Pattern)是一种创建型操持模式,它通过复制现有对象来创建新对象,而不是通过new关键字实例化。
核心特点


  • 克隆代替新建:通过复制现有对象创建新实例
  • 性能上风:制止昂贵的初始化过程
  • 机动性:运行时动态改变对象范例
  • 简化创建:潜伏对象创建细节
二、原型模式的实现方式

1. 根本实现(浅拷贝)
  1. // 实现Cloneable接口
  2. public class Sheep implements Cloneable {
  3.     private String name;
  4.     private int age;
  5.    
  6.     public Sheep(String name, int age) {
  7.         this.name = name;
  8.         this.age = age;
  9.     }
  10.    
  11.     // 重写clone方法
  12.     @Override
  13.     public Sheep clone() {
  14.         try {
  15.             return (Sheep) super.clone();
  16.         } catch (CloneNotSupportedException e) {
  17.             throw new AssertionError();
  18.         }
  19.     }
  20.    
  21.     // getter和setter
  22.     public String getName() {
  23.         return name;
  24.     }
  25. }
  26. // 使用示例
  27. Sheep original = new Sheep("Dolly", 2);
  28. Sheep cloned = original.clone();
复制代码
2. 深拷贝实现
  1. public class DeepCloneExample implements Cloneable {
  2.     private String data;
  3.     private List<String> items;
  4.    
  5.     public DeepCloneExample(String data, List<String> items) {
  6.         this.data = data;
  7.         this.items = new ArrayList<>(items);
  8.     }
  9.    
  10.     @Override
  11.     public DeepCloneExample clone() {
  12.         try {
  13.             DeepCloneExample cloned = (DeepCloneExample) super.clone();
  14.             // 对引用类型进行深拷贝
  15.             cloned.items = new ArrayList<>(this.items);
  16.             return cloned;
  17.         } catch (CloneNotSupportedException e) {
  18.             throw new AssertionError();
  19.         }
  20.     }
  21. }
复制代码
3. 使用序列化实现深拷贝
  1. import java.io.*;
  2. public class DeepCopySerializable implements Serializable {
  3.     private String name;
  4.     private Date birthDate;
  5.    
  6.     public DeepCopySerializable deepCopy() {
  7.         try {
  8.             ByteArrayOutputStream bos = new ByteArrayOutputStream();
  9.             ObjectOutputStream oos = new ObjectOutputStream(bos);
  10.             oos.writeObject(this);
  11.             
  12.             ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
  13.             ObjectInputStream ois = new ObjectInputStream(bis);
  14.             return (DeepCopySerializable) ois.readObject();
  15.         } catch (Exception e) {
  16.             throw new RuntimeException("深拷贝失败", e);
  17.         }
  18.     }
  19. }
复制代码
三、原型模式的应用场景

1. 对象初始化本钱高
  1. public class ExpensiveObject implements Cloneable {
  2.     private String data;
  3.     private List<String> cachedResults;
  4.    
  5.     public ExpensiveObject() {
  6.         // 模拟耗时初始化
  7.         this.data = loadDataFromDatabase();
  8.         this.cachedResults = computeExpensiveResults();
  9.     }
  10.    
  11.     @Override
  12.     public ExpensiveObject clone() {
  13.         try {
  14.             return (ExpensiveObject) super.clone();
  15.         } catch (CloneNotSupportedException e) {
  16.             throw new AssertionError();
  17.         }
  18.     }
  19. }
  20. // 使用示例
  21. ExpensiveObject prototype = new ExpensiveObject();
  22. ExpensiveObject copy = prototype.clone();
复制代码
2. 游戏开发中的脚色克隆
  1. public abstract class GameCharacter implements Cloneable {
  2.     protected String name;
  3.     protected int health;
  4.     protected List<Item> inventory;
  5.    
  6.     @Override
  7.     public GameCharacter clone() {
  8.         try {
  9.             GameCharacter clone = (GameCharacter) super.clone();
  10.             // 深拷贝inventory
  11.             clone.inventory = new ArrayList<>(this.inventory);
  12.             return clone;
  13.         } catch (CloneNotSupportedException e) {
  14.             throw new AssertionError();
  15.         }
  16.     }
  17.    
  18.     public abstract void render();
  19. }
复制代码
3. 设置对象复制
  1. public class SystemConfig implements Cloneable {
  2.     private String theme;
  3.     private int timeout;
  4.     private Map<String, String> preferences;
  5.    
  6.     @Override
  7.     public SystemConfig clone() {
  8.         try {
  9.             SystemConfig clone = (SystemConfig) super.clone();
  10.             // 深拷贝Map
  11.             clone.preferences = new HashMap<>(this.preferences);
  12.             return clone;
  13.         } catch (CloneNotSupportedException e) {
  14.             throw new AssertionError();
  15.         }
  16.     }
  17. }
复制代码
四、原型模式的变体

1. 原型管理器
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. public class PrototypeManager {
  4.     private static Map<String, Cloneable> prototypes = new HashMap<>();
  5.    
  6.     static {
  7.         prototypes.put("default", new DefaultPrototype());
  8.         prototypes.put("custom", new CustomPrototype());
  9.     }
  10.    
  11.     public static Cloneable getPrototype(String type) {
  12.         return prototypes.get(type).clone();
  13.     }
  14. }
复制代码
2. 联合工厂方法
  1. public abstract class Shape implements Cloneable {
  2.     public abstract void draw();
  3.    
  4.     @Override
  5.     public Shape clone() {
  6.         try {
  7.             return (Shape) super.clone();
  8.         } catch (CloneNotSupportedException e) {
  9.             throw new AssertionError();
  10.         }
  11.     }
  12. }
  13. public class ShapeFactory {
  14.     private static Map<String, Shape> shapeMap = new HashMap<>();
  15.    
  16.     static {
  17.         shapeMap.put("circle", new Circle());
  18.         shapeMap.put("square", new Square());
  19.     }
  20.    
  21.     public static Shape getShape(String type) {
  22.         return shapeMap.get(type).clone();
  23.     }
  24. }
复制代码
五、原型模式的留意事项


  • 深拷贝与浅拷贝

    • 浅拷贝:根本范例复制值,引用范例复制引用
    • 深拷贝:引用范例也创建新对象

  • Cloneable接口题目

    • clone()方法是Object类的protected方法
    • 必要重写为public方法
    • 思量使用复制构造函数或工厂方法更换

  • final字段题目

    • 克隆后无法修改final字段的值
    • 必要特别留意final引用范例的字段

六、原型模式的优缺点

优点


  • 性能提拔:制止昂贵的初始化过程
  • 简化创建:潜伏对象创建细节
  • 动态性:运行时决定实例范例
  • 镌汰子类:不必要为每种对象创建子类
缺点


  • 深拷贝复杂性:必要处置处罚引用对象的复制
  • clone方法限定:必要实现Cloneable接口
  • 构造逻辑分散:初始化逻辑大概分布在构造函数和clone方法中
七、最佳实践


  • 思量深拷贝需求:明确是否必要深拷贝
  • 文档化clone活动:明确分析clone方法的实现方式
  • 更换方案:思量使用复制构造函数或静态工厂方法
  • 不可变对象:原型模式特别得当不可变对象
  • 联合其他模式:可与工厂方法、享元模式联合使用
八、总结

原型模式是创建型模式中独特的一种,它通过复制而非新建的方式创建对象,实用于:

  • 对象创建本钱高的场景
  • 必要动态设置对象的场景
  • 必要隔离对象创建细节的场景
在实际开发中,原型模式常见于:

  • 游戏开发(脚色、道具复制)
  • 设置管理(设置模板复制)
  • 缓存实现(原型缓存)
  • 打消/重做功能(状态生存与规复)
正确使用原型模式可以显着进步体系性能,但必要留意深拷贝/浅拷贝的选择以及clone方法的正确实现。
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表