原型模式(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;  
}
相关推荐
肆忆_12 小时前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星16 小时前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛2 天前
delete又未完全delete
c++
端平入洛3 天前
auto有时不auto
c++
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20214 天前
信号量和信号
linux·c++
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc