原型模式(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;  
}
相关推荐
悟能不能悟1 天前
java的java.sql.Date和java.util.Date的区别,应该怎么使用
java·开发语言
循环过三天1 天前
3.4、Python-集合
开发语言·笔记·python·学习·算法
_院长大人_1 天前
设计模式-工厂模式
java·开发语言·设计模式
MATLAB代码顾问1 天前
MATLAB实现决策树数值预测
开发语言·决策树·matlab
不染尘.1 天前
2025_11_7_刷题
开发语言·c++·vscode·算法
似水এ᭄往昔1 天前
【C++】--stack和queue
开发语言·c++
仰望—星空1 天前
MiniEngine学习笔记 : CommandListManager
c++·windows·笔记·学习·cg·direct3d
csbysj20201 天前
R 绘图 - 散点图
开发语言
会跑的兔子1 天前
Android 16 Kotlin协程 第一部分
android·开发语言·kotlin
Js_cold1 天前
Verilog函数function
开发语言·fpga开发·verilog