当前位置: 首页 > news >正文

设计模式 八:原型模式 (Prototype Pattern)

动机(Motivation)

1、在软件系统中,经常面临着“某些结构复杂的对象”的创建工作;由于需求的变化,这些对象经常面临着剧烈的变化,但是它们却拥有比较稳定一致的接口。
2、如何应对这种变化?如何向“客户程序(使用这些对象的程序)”隔离出“这些易变对象”,从而使得“依赖这些易变对象的客户程序”不随着需求改变而改变?

解决方法:使用原型模式

原型模式是一种创建型设计模式,它允许通过复制现有对象来创建新对象,而不是通过构造函数创建。 

基本概念

原型模式的核心思想是:

  • 创建一个原型接口,声明克隆方法

  • 具体类实现这个接口并提供克隆自身的能力

  • 客户端通过请求原型对象克隆自身来创建新对象

实现方式

1. 基本实现

#include <iostream>
#include <memory>// 原型基类
class Prototype {
public:virtual ~Prototype() = default;virtual std::unique_ptr<Prototype> clone() const = 0;virtual void print() const = 0;
};// 具体原型类
class ConcretePrototype : public Prototype {
public:ConcretePrototype(int value) : value_(value) {}// 复制构造函数实现克隆std::unique_ptr<Prototype> clone() const override {return std::make_unique<ConcretePrototype>(*this);}void print() const override {std::cout << "ConcretePrototype with value: " << value_ << std::endl;}void setValue(int value) {value_ = value;}private:int value_;
};int main() {// 创建原型对象auto prototype = std::make_unique<ConcretePrototype>(10);// 克隆对象auto clone1 = prototype->clone();auto clone2 = prototype->clone();// 修改克隆对象dynamic_cast<ConcretePrototype*>(clone1.get())->setValue(20);dynamic_cast<ConcretePrototype*>(clone2.get())->setValue(30);// 输出结果prototype->print();  // 输出: ConcretePrototype with value: 10clone1->print();     // 输出: ConcretePrototype with value: 20clone2->print();     // 输出: ConcretePrototype with value: 30return 0;
}

2. 使用原型管理器

#include <iostream>
#include <memory>
#include <unordered_map>class Prototype {
public:virtual ~Prototype() = default;virtual std::unique_ptr<Prototype> clone() const = 0;virtual void print() const = 0;
};class ConcretePrototypeA : public Prototype {
public:ConcretePrototypeA(int value) : value_(value) {}std::unique_ptr<Prototype> clone() const override {return std::make_unique<ConcretePrototypeA>(*this);}void print() const override {std::cout << "ConcretePrototypeA with value: " << value_ << std::endl;}private:int value_;
};class ConcretePrototypeB : public Prototype {
public:ConcretePrototypeB(std::string str) : str_(std::move(str)) {}std::unique_ptr<Prototype> clone() const override {return std::make_unique<ConcretePrototypeB>(*this);}void print() const override {std::cout << "ConcretePrototypeB with string: " << str_ << std::endl;}private:std::string str_;
};class PrototypeManager {
public:void registerPrototype(const std::string& key, std::unique_ptr<Prototype> prototype) {prototypes_[key] = std::move(prototype);}std::unique_ptr<Prototype> create(const std::string& key) {if (prototypes_.find(key) != prototypes_.end()) {return prototypes_[key]->clone();}return nullptr;}private:std::unordered_map<std::string, std::unique_ptr<Prototype>> prototypes_;
};int main() {PrototypeManager manager;// 注册原型manager.registerPrototype("A", std::make_unique<ConcretePrototypeA>(100));manager.registerPrototype("B", std::make_unique<ConcretePrototypeB>("Hello"));// 从原型创建对象auto obj1 = manager.create("A");auto obj2 = manager.create("B");auto obj3 = manager.create("A");if (obj1) obj1->print();  // 输出: ConcretePrototypeA with value: 100if (obj2) obj2->print();  // 输出: ConcretePrototypeB with string: Helloif (obj3) obj3->print();  // 输出: ConcretePrototypeA with value: 100return 0;
}

 UML结构

 

原型模式的优点

  1. 减少子类数量:不需要为每种对象创建专门的子类

  2. 动态配置应用:可以在运行时添加或删除原型

  3. 简化对象创建:特别是当对象初始化过程复杂时

  4. 性能优化:克隆通常比新建对象更高效

适用场景

  1. 当系统需要独立于其产品的创建、组合和表示时

  2. 当要实例化的类是在运行时指定时

  3. 当需要避免建立与产品类层次平行的工厂类层次时

  4. 当一个类的实例只能有几个不同状态组合中的一种时

注意事项

  1. 深拷贝与浅拷贝问题:确保克隆操作正确地复制了所有成员变量

  2. 对于包含循环引用的对象,需要特别处理克隆逻辑

  3. 原型模式可能隐藏了对象的创建细节,使代码更难理解

原型模式在C++中特别有用,因为它可以利用拷贝构造函数和赋值操作符来实现克隆操作,同时结合智能指针可以很好地管理内存。

http://www.lryc.cn/news/597720.html

相关文章:

  • java设计模式 -【装饰器模式】
  • AI营销核心技术解析:运作机制与行业应用实例
  • 在模拟器上实现 GRE 实验
  • HCIP一二章笔记
  • 动态路由协议基础
  • HF86611_VB1/HF86611Q_VB1:多通道USB HiFi音频解码器固件技术解析
  • 0基础法考随手笔记 02(刑诉法专题04 辩护与代理)
  • 音视频中一些常见的知识点
  • 机器学习与视觉结合开发基础
  • 设备虚拟化技术
  • 漏洞扫描系列03:导出PDF/HTML报告
  • 如何Visual Studio 的配置从 Qt-Debug 切换到 x64-Debug
  • 定义损失函数并以此训练和评估模型
  • DPVR亮相青岛品牌日,崂山科创力量引领AI眼镜新浪潮
  • 广告业技术范式转移:当AI开始重构整个价值链
  • 基于YOLOv5+pyQT6的目标检测系统通用项目模板
  • 指针的大小是多少?
  • 电子公章怎么弄到合同上?2025最新指南
  • 负压产生电路分析
  • 【AI News | 20250722】每日AI进展
  • 借助DataStream和多路复用实现可观察性
  • 如何用 Kafka + Redis + 线程池搭建高吞吐异步消息处理架构
  • 解决 i.MX6ULL 通过 ADB 连接时权限不足问题 not in the plugdev group
  • C 语言介绍
  • 环境搭建①:下载STM32标准外设库(固件库下载)
  • J2EE模式---视图助手模式
  • Tomcat项目部署(单体、聚合项目)
  • LLM中词嵌入向量的 模长 和 角度 的物理含义
  • 【JavaScript】window.location用法
  • 【Vue3】ECharts图表案例