跳转到内容

原型模式(Prototype Pattern)

来自代码酷


原型模式是一种创建型设计模式,它通过复制现有对象(原型)来创建新对象,而不是通过类实例化。这种方式避免了重复初始化对象的开销,尤其适用于创建成本较高的对象或需要动态配置的场景。

核心概念[编辑 | 编辑源代码]

原型模式的核心是**原型接口**(通常为Cloneable),它声明了一个克隆方法(如clone())。具体原型类实现此接口,并定义如何复制自身的逻辑。

模式结构[编辑 | 编辑源代码]

classDiagram class Prototype { <<interface>> +clone(): Prototype } class ConcretePrototype { -field: Any +clone(): Prototype } Prototype <|-- ConcretePrototype

  • Prototype:声明克隆方法的接口或抽象类。
  • ConcretePrototype:实现克隆方法的具体类。

代码示例[编辑 | 编辑源代码]

以下是一个Java实现的简单示例:

// 1. 声明原型接口
interface Prototype extends Cloneable {
    Prototype clone() throws CloneNotSupportedException;
}

// 2. 实现具体原型类
class ConcretePrototype implements Prototype {
    private String field;

    public ConcretePrototype(String field) {
        this.field = field;
    }

    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (ConcretePrototype) super.clone(); // 浅拷贝
    }

    public String getField() {
        return field;
    }
}

// 3. 客户端使用
public class Client {
    public static void main(String[] args) throws CloneNotSupportedException {
        ConcretePrototype original = new ConcretePrototype("初始值");
        ConcretePrototype copy = (ConcretePrototype) original.clone();

        System.out.println("Original field: " + original.getField());
        System.out.println("Copied field: " + copy.getField());
    }
}

输出结果:

Original field: 初始值
Copied field: 初始值

关键点说明[编辑 | 编辑源代码]

  • 通过clone()方法复制对象时,默认是浅拷贝(仅复制基本类型和引用地址)。
  • 如需深拷贝(递归复制引用对象),需重写clone()方法手动实现。

实际应用场景[编辑 | 编辑源代码]

场景1:游戏中的敌人生成[编辑 | 编辑源代码]

在游戏中,同类型敌人(如小兵)可能有相同的初始属性但不同位置。使用原型模式可快速复制基础模板:

class Enemy implements Cloneable {
    private String type;
    private int health;

    public Enemy(String type, int health) {
        this.type = type;
        this.health = health;
    }

    @Override
    public Enemy clone() {
        return new Enemy(this.type, this.health); // 深拷贝
    }
}

// 使用时:
Enemy skeletonTemplate = new Enemy("骷髅", 50);
Enemy skeleton1 = skeletonTemplate.clone();

场景2:配置对象复用[编辑 | 编辑源代码]

当系统需要多个配置相似的对象时(如数据库连接参数),可通过原型避免重复初始化:

import copy

class DBConnection:
    def __init__(self, host, user, password):
        self.host = host
        self.user = user
        self.password = password

    def clone(self):
        return copy.deepcopy(self)

# 基础配置模板
base_config = DBConnection("localhost", "admin", "123456")
dev_config = base_config.clone()
dev_config.host = "dev-db.example.com"

深拷贝 vs 浅拷贝[编辑 | 编辑源代码]

flowchart LR A[原型对象] -->|浅拷贝| B[新对象] A --> C[引用对象] B --> C D[原型对象] -->|深拷贝| E[新对象] D --> F[引用对象] E --> G[新引用对象副本]

  • 浅拷贝问题示例:
class ShallowCopyExample implements Cloneable {
    List<String> items = new ArrayList<>();

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone(); // 默认浅拷贝
    }
}

修改拷贝对象的items会影响原对象!

数学建模[编辑 | 编辑源代码]

原型模式可形式化为: clone(p)={p浅拷贝deepCopy(p)深拷贝 其中deepCopy需递归处理所有引用字段。

优缺点[编辑 | 编辑源代码]

原型模式分析
优点 缺点
避免重复初始化开销 深拷贝实现复杂
动态添加或删除产品 需小心循环引用
隐藏创建细节 可能违反"里氏替换原则"

与其他模式的关系[编辑 | 编辑源代码]

  • 工厂方法模式:都用于创建对象,但原型模式通过复制,工厂方法通过子类化。
  • 单例模式:注意原型模式可能破坏单例的唯一性。

模板:设计模式导航