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;
}
相关推荐
isNotNullX1 天前
企业数据中台建设,ETL工具选错了会踩哪些坑?
数据仓库·etl·原型模式
半个烧饼不加肉1 天前
JS 底层探究-- 普通函数和构造函数
开发语言·javascript·原型模式
折哥的程序人生 · 物流技术专研3 天前
Java 23 种设计模式:从踩坑到精通 | 原型模式 —— 克隆对象,深拷贝与浅拷贝的坑你踩过吗?
java·设计模式·架构·原型模式·单一职责原则
ourenjiang4 天前
【学习设计模式】原型模式
学习·设计模式·原型模式
迷藏4946 天前
Python+DuckDB:轻量级BI流水线实战
java·开发语言·python·原型模式
J2虾虾10 天前
Spring AI Alibaba - 检索增强生成(RAG)
人工智能·spring·原型模式
skywalk816312 天前
根据言律的语法,能否用racket进行开发呢?主要探讨是否可行。 racket在这里:E:\Program Files\Racket\Racket.exe
开发语言·原型模式
invicinble14 天前
设计模式(类的拓扑结构)(描述总纲)
设计模式·原型模式
UXbot14 天前
初创公司如何选择合适的UI工具支撑快速迭代产品?
人工智能·低代码·ios·交互·原型模式
之歆15 天前
Day18_JavaScript高级核心:原型链、继承与事件循环机制深度解析(上)
开发语言·javascript·原型模式