Prototype Pattern

Prototype Pattern

Intent : Use prototype instances to specify the type of objects to be created, and create new objects by copying these prototypes.
Main issue addressed: Dynamically create and delete prototypes at runtime.

used in qt:

复制代码
QTableWidgetItem *QTableWidgetItem::clone() const

some codes:

复制代码
#include <iostream>
#include <memory>  // For std::unique_ptr
#include <string>

// Prototype class template

template <typename T>
class Prototype {
public:

    virtual ~Prototype() = default;

    // Virtual method to clone the object
    virtual std::unique_ptr<T> clone() const = 0;

    // A method to display object information (can be customized)
    virtual void display() const = 0;
};

// ConcretePrototype class template

class ConcretePrototype : public Prototype<ConcretePrototype> {
private:
    std::string name;

public:
    explicit ConcretePrototype(const std::string& name) : name(name) {}

    // Override the clone function to return a copy of the current object
    std::unique_ptr<ConcretePrototype> clone() const override {
        return std::make_unique<ConcretePrototype>(*this); // Create a new object as a copy of the current one
    }

    void display() const override {
        std::cout << "ConcretePrototype name: " << name << std::endl;
    }
};
int main() {
    // Create an original prototype object
    auto original = std::make_unique<ConcretePrototype>("Original");

    // Display the original object
    original->display();

    // Clone the object
    auto clone1 = original->clone();
    clone1->display(); // Display the cloned object

    // Clone again
    auto clone2 = original->clone();
    clone2->display(); // Display another cloned object

    return 0;
}
相关推荐
程序边界10 天前
一台数据集成软件的拆解笔记(上):把 KFS 装起来、跑起来,再挑一堆毛病
笔记·原型模式
General_G14 天前
创建型模式—原型(Prototype)模式
c++·设计模式·原型模式
冒险的豆子20 天前
JS 原型链 通俗易懂 解释说明(类比 关系)
开发语言·javascript·原型模式
吠品1 个月前
箭头函数为什么不能 new
开发语言·javascript·原型模式
2603_965896621 个月前
JS原型与原型链|对象继承与实例底层原理
开发语言·javascript·原型模式
YYYing.1 个月前
【设计模式系列 (五) 】原型模式
开发语言·后端·设计模式·原型模式·c/c++
羞儿2 个月前
【读点论文】Overall positive prototype for few-shot open-set recognition
原型模式·小样本学习·特征优化·开集学习
liangshanbo12152 个月前
手写 Function.prototype.call 与 Function.prototype.apply 面试题满分答案
开发语言·javascript·原型模式
江畔柳前堤2 个月前
云原生 × AI 全景图谱:从 Kubernetes 到 Agent 基础设施的一次认知跃迁
人工智能·分布式·gpt·云原生·kubernetes·原型模式·agi
艾伦野鸽ggg2 个月前
JavaScript 原型链与原型对象详解
javascript·原型模式