模式定义
原型模式(Prototype Pattern)是一种创建型设计模式,它通过克隆现有对象来创建新对象,避免重复执行初始化逻辑[1][2][4]。该模式的核心是将对象创建过程委托给对象自身,通过统一的克隆接口实现灵活复制[3][6][8]。
模式结构
抽象原型类(Prototype)
- 定义克隆接口
clone()
,强制所有具体原型实现复制逻辑。
具体原型类(ConcretePrototype) - 实现
clone()
方法,通过拷贝构造函数或深拷贝生成新对象。
客户端(Client) - 通过调用原型对象的
clone()
方法创建新对象,无需依赖具体类。
适用场景
复杂对象初始化成本高:如数控系统中加工任务的参数配置。
动态生成相似对象:批量创建仅部分参数不同的加工指令。
避免工厂类层次结构:直接通过原型克隆替代子类化。
C++示例(数控系统场景)
场景说明:
数控系统需要快速复制已有的加工任务模板(如刀具路径、速度参数),生成新任务并调整部分参数。
#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()
,符合开闭原则。
优缺点对比
优点 | 缺点 |
---|---|
减少重复初始化开销 | 深拷贝实现复杂(含指针/资源时) |
动态生成复杂对象 | 每个类需实现克隆方法,增加代码量 |