原型模式(C++)

**定义:**原型模式是一种创建型设计模式,它允许通过复制(或克隆)一个已经存在的对象来创建一个新的对象,而无需重新实例化它。这通常是通过实现一个原型接口,该接口声明一个克隆方法,然后在具体类中实现这个方法来完成的。

代码:

cpp 复制代码
// 原型基类  
class Prototype {  
public:  
    virtual ~Prototype() = default;  
    virtual std::shared_ptr<Prototype> clone() const = 0; // 纯虚函数,要求派生类实现  
    virtual void show() const = 0; // 用于展示对象状态的纯虚函数  
};  
  
// 具体原型1  
class ConcretePrototype1 : public Prototype {  
private:  
    std::string name;  
public:  
    ConcretePrototype1(const std::string& n) : name(n) {}  
    std::shared_ptr<Prototype> clone() const override {  
        return std::make_shared<ConcretePrototype1>(*this); // 浅拷贝  
    }  
    void show() const override {  
        std::cout << "ConcretePrototype1 name: " << name << std::endl;  
    }  
};  
  
// 具体原型2  
class ConcretePrototype2 : public Prototype {  
private:  
    int value;  
public:  
    ConcretePrototype2(int v) : value(v) {}  
    std::shared_ptr<Prototype> clone() const override {  
        return std::make_shared<ConcretePrototype2>(*this); // 浅拷贝  
    }  
    void show() const override {  
        std::cout << "ConcretePrototype2 value: " << value << std::endl;  
    }  
};  
  
int main() {  
    std::shared_ptr<Prototype> proto1 = std::make_shared<ConcretePrototype1>("Prototype1");  
    std::shared_ptr<Prototype> proto2 = std::make_shared<ConcretePrototype2>(42);  
  
    proto1->show();  
    proto2->show();  
  
    // 克隆对象  
    std::shared_ptr<Prototype> clone1 = proto1->clone();  
    std::shared_ptr<Prototype> clone2 = proto2->clone();  
  
    clone1->show();  
    clone2->show();  
  
    return 0;  
}
相关推荐
果汁华4 分钟前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
小小晓.23 分钟前
C++:语句和作用域
开发语言·c++
fqbqrr35 分钟前
2607C++,soui,xplayer视频播放器
c++·soui
wanderist.1 小时前
Lambda表达式在算法竞赛中的应用
java·开发语言·算法
zh路西法2 小时前
【10天速通ROS2-PX4无人机】(四) 关掉GPS和气压计,纯激光定位还能飞吗
c++·无人机·px4·ros2·卡尔曼滤波·fastlio2
海天鹰2 小时前
PHP上传文件
android·开发语言·php
yyds_yyd_100863 小时前
1464. 数组中两元素的最大乘积(2026.07.27)
数据结构·c++·算法·leetcode
Yeauty4 小时前
渲染成图再 CLI 拼接,还是进程内直推?Rust 帧到视频的两条路
开发语言·rust·音视频
geovindu4 小时前
CSharp: Breadth First Search Algorithm and Depth First Search Algorithm
开发语言·后端·算法·c#·.net·搜索算法
库克克5 小时前
【C++】set 与multiset
开发语言·c++