23种设计模式 - 原型模式

模式定义

原型模式(Prototype Pattern)是一种创建型设计模式,它通过克隆现有对象来创建新对象,避免重复执行初始化逻辑[1][2][4]。该模式的核心是将对象创建过程委托给对象自身,通过统一的克隆接口实现灵活复制[3][6][8]。


模式结构

抽象原型类(Prototype)

  • 定义克隆接口 clone(),强制所有具体原型实现复制逻辑。
    具体原型类(ConcretePrototype)
  • 实现 clone() 方法,通过拷贝构造函数或深拷贝生成新对象。
    客户端(Client)
  • 通过调用原型对象的 clone() 方法创建新对象,无需依赖具体类。

适用场景

复杂对象初始化成本高:如数控系统中加工任务的参数配置。

动态生成相似对象:批量创建仅部分参数不同的加工指令。

避免工厂类层次结构:直接通过原型克隆替代子类化。


C++示例(数控系统场景)

场景说明:

数控系统需要快速复制已有的加工任务模板(如刀具路径、速度参数),生成新任务并调整部分参数。

cpp 复制代码
#include 
#include 
#include 

// 抽象原型类:加工任务
class MachiningTask {
public:
    virtual ~MachiningTask() = default;
    virtual std::unique_ptr clone() const = 0;
    virtual void execute() const = 0;
    virtual void setToolPath(const std::string& path) = 0;
};

// 具体原型类:钻孔任务
class DrillingTask : public MachiningTask {
private:
    std::string toolPath_;
    int speed_;

public:
    DrillingTask(const std::string& path, int speed) 
        : toolPath_(path), speed_(speed) {}

    // 拷贝构造函数(深拷贝)
    DrillingTask(const DrillingTask& other) 
        : toolPath_(other.toolPath_), speed_(other.speed_) {}

    std::unique_ptr clone() const override {
        return std::make_unique(*this);  // 调用拷贝构造[3][7]
    }

    void execute() const override {
        std::cout << "执行钻孔任务:路径=" << toolPath_ 
                  << ", 转速=" << speed_ << "rpm" << std::endl;
    }

    void setToolPath(const std::string& path) override {
        toolPath_ = path;
    }
};

int main() {
    // 创建原型对象(模板任务)
    auto originalTask = DrillingTask("A1→B2→C3", 1500);
    
    // 克隆任务并修改参数
    auto newTask = originalTask.clone();
    newTask->setToolPath("X10→Y20→Z5");
    newTask->execute();  // 输出:执行钻孔任务:路径=X10→Y20→Z5, 转速=1500rpm

    return 0;
}

关键点分析

深拷贝实现

  • 通过拷贝构造函数复制所有成员变量,确保克隆对象与原对象独立。
    智能指针管理
  • 使用 std::unique_ptr 自动释放克隆对象,避免内存泄漏。
    灵活扩展
  • 新增任务类型(如铣削任务)只需继承 MachiningTask 并实现 clone(),符合开闭原则。

优缺点对比

优点 缺点
减少重复初始化开销 深拷贝实现复杂(含指针/资源时)
动态生成复杂对象 每个类需实现克隆方法,增加代码量
相关推荐
We་ct21 小时前
JS手撕:函数进阶 & 设计模式解析
开发语言·前端·javascript·设计模式·面试·前端框架
冷小鱼1 天前
设计模式全景指南:23种模式深度解析与Python实现
设计模式
楼田莉子1 天前
设计模式:创建型设计模式简介
服务器·开发语言·c++·设计模式
UrSpecial1 天前
设计模式:观察者模式
观察者模式·设计模式
zhaoshuzhaoshu1 天前
设计模式之结构型设计模式详解
python·设计模式
倒流时光三十年1 天前
重学设计模式 之 流式 Builder 模式(Fluent Builder)
设计模式·流式 builder·fluent builder
IT枫斗者1 天前
AI Agent 设计模式全景解析:从单体智能到分布式协作的架构演进
人工智能·redis·分布式·算法·spring·缓存·设计模式
UXbot2 天前
AI原型设计工具评测:从创意到交互式Demo,5款产品全面解析
前端·ui·设计模式·ai·ai编程·原型模式