马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
原型模式详解
一、原型模式概述
原型模式(Prototype Pattern)是一种创建型操持模式,它通过复制现有对象来创建新对象,而不是通过new关键字实例化。
核心特点
- 克隆代替新建:通过复制现有对象创建新实例
- 性能上风:制止昂贵的初始化过程
- 机动性:运行时动态改变对象范例
- 简化创建:潜伏对象创建细节
二、原型模式的实现方式
1. 根本实现(浅拷贝)
- // 实现Cloneable接口
- public class Sheep implements Cloneable {
- private String name;
- private int age;
-
- public Sheep(String name, int age) {
- this.name = name;
- this.age = age;
- }
-
- // 重写clone方法
- @Override
- public Sheep clone() {
- try {
- return (Sheep) super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError();
- }
- }
-
- // getter和setter
- public String getName() {
- return name;
- }
- }
- // 使用示例
- Sheep original = new Sheep("Dolly", 2);
- Sheep cloned = original.clone();
复制代码 2. 深拷贝实现
- public class DeepCloneExample implements Cloneable {
- private String data;
- private List<String> items;
-
- public DeepCloneExample(String data, List<String> items) {
- this.data = data;
- this.items = new ArrayList<>(items);
- }
-
- @Override
- public DeepCloneExample clone() {
- try {
- DeepCloneExample cloned = (DeepCloneExample) super.clone();
- // 对引用类型进行深拷贝
- cloned.items = new ArrayList<>(this.items);
- return cloned;
- } catch (CloneNotSupportedException e) {
- throw new AssertionError();
- }
- }
- }
复制代码 3. 使用序列化实现深拷贝
- import java.io.*;
- public class DeepCopySerializable implements Serializable {
- private String name;
- private Date birthDate;
-
- public DeepCopySerializable deepCopy() {
- try {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutputStream oos = new ObjectOutputStream(bos);
- oos.writeObject(this);
-
- ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
- ObjectInputStream ois = new ObjectInputStream(bis);
- return (DeepCopySerializable) ois.readObject();
- } catch (Exception e) {
- throw new RuntimeException("深拷贝失败", e);
- }
- }
- }
复制代码 三、原型模式的应用场景
1. 对象初始化本钱高
- public class ExpensiveObject implements Cloneable {
- private String data;
- private List<String> cachedResults;
-
- public ExpensiveObject() {
- // 模拟耗时初始化
- this.data = loadDataFromDatabase();
- this.cachedResults = computeExpensiveResults();
- }
-
- @Override
- public ExpensiveObject clone() {
- try {
- return (ExpensiveObject) super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError();
- }
- }
- }
- // 使用示例
- ExpensiveObject prototype = new ExpensiveObject();
- ExpensiveObject copy = prototype.clone();
复制代码 2. 游戏开发中的脚色克隆
- public abstract class GameCharacter implements Cloneable {
- protected String name;
- protected int health;
- protected List<Item> inventory;
-
- @Override
- public GameCharacter clone() {
- try {
- GameCharacter clone = (GameCharacter) super.clone();
- // 深拷贝inventory
- clone.inventory = new ArrayList<>(this.inventory);
- return clone;
- } catch (CloneNotSupportedException e) {
- throw new AssertionError();
- }
- }
-
- public abstract void render();
- }
复制代码 3. 设置对象复制
- public class SystemConfig implements Cloneable {
- private String theme;
- private int timeout;
- private Map<String, String> preferences;
-
- @Override
- public SystemConfig clone() {
- try {
- SystemConfig clone = (SystemConfig) super.clone();
- // 深拷贝Map
- clone.preferences = new HashMap<>(this.preferences);
- return clone;
- } catch (CloneNotSupportedException e) {
- throw new AssertionError();
- }
- }
- }
复制代码 四、原型模式的变体
1. 原型管理器
- import java.util.HashMap;
- import java.util.Map;
- public class PrototypeManager {
- private static Map<String, Cloneable> prototypes = new HashMap<>();
-
- static {
- prototypes.put("default", new DefaultPrototype());
- prototypes.put("custom", new CustomPrototype());
- }
-
- public static Cloneable getPrototype(String type) {
- return prototypes.get(type).clone();
- }
- }
复制代码 2. 联合工厂方法
- public abstract class Shape implements Cloneable {
- public abstract void draw();
-
- @Override
- public Shape clone() {
- try {
- return (Shape) super.clone();
- } catch (CloneNotSupportedException e) {
- throw new AssertionError();
- }
- }
- }
- public class ShapeFactory {
- private static Map<String, Shape> shapeMap = new HashMap<>();
-
- static {
- shapeMap.put("circle", new Circle());
- shapeMap.put("square", new Square());
- }
-
- public static Shape getShape(String type) {
- return shapeMap.get(type).clone();
- }
- }
复制代码 五、原型模式的留意事项
- 深拷贝与浅拷贝
- 浅拷贝:根本范例复制值,引用范例复制引用
- 深拷贝:引用范例也创建新对象
- Cloneable接口题目
- clone()方法是Object类的protected方法
- 必要重写为public方法
- 思量使用复制构造函数或工厂方法更换
- final字段题目
- 克隆后无法修改final字段的值
- 必要特别留意final引用范例的字段
六、原型模式的优缺点
优点
- 性能提拔:制止昂贵的初始化过程
- 简化创建:潜伏对象创建细节
- 动态性:运行时决定实例范例
- 镌汰子类:不必要为每种对象创建子类
缺点
- 深拷贝复杂性:必要处置处罚引用对象的复制
- clone方法限定:必要实现Cloneable接口
- 构造逻辑分散:初始化逻辑大概分布在构造函数和clone方法中
七、最佳实践
- 思量深拷贝需求:明确是否必要深拷贝
- 文档化clone活动:明确分析clone方法的实现方式
- 更换方案:思量使用复制构造函数或静态工厂方法
- 不可变对象:原型模式特别得当不可变对象
- 联合其他模式:可与工厂方法、享元模式联合使用
八、总结
原型模式是创建型模式中独特的一种,它通过复制而非新建的方式创建对象,实用于:
- 对象创建本钱高的场景
- 必要动态设置对象的场景
- 必要隔离对象创建细节的场景
在实际开发中,原型模式常见于:
- 游戏开发(脚色、道具复制)
- 设置管理(设置模板复制)
- 缓存实现(原型缓存)
- 打消/重做功能(状态生存与规复)
正确使用原型模式可以显着进步体系性能,但必要留意深拷贝/浅拷贝的选择以及clone方法的正确实现。
|