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;
}
相关推荐
UXbot2 天前
AI原型设计工具评测:从创意到交互式Demo,5款产品全面解析
前端·ui·设计模式·ai·ai编程·原型模式
xiaotao1312 天前
JS new 操作符完整执行过程
开发语言·前端·javascript·原型模式
UXbot3 天前
2026年AI全链路产品开发工具对比:5款从创意到上线一站式平台深度解析
前端·ui·kotlin·软件构建·swift·原型模式
前端郭德纲5 天前
JavaScript 原型相关属性详解
开发语言·javascript·原型模式
yaaakaaang5 天前
五、原型模式
java·原型模式
时寒的笔记5 天前
js基础05_js类、原型对象、原型链&案例(解决无限debugger)
开发语言·javascript·原型模式
weixin_307779138 天前
使用COPY INTO从S3导入CSV文件到Snowflake表的问题分析与自动化验证方案
运维·自动化·原型模式
UXbot9 天前
UXbot 是什么?一句指令生成完整应用的 AI 工具
前端·ai·交互·个人开发·ai编程·原型模式·ux
WZTTMoon10 天前
Spring Prototype Bean的四种正确使用方式
spring·原型模式
bmseven18 天前
23种设计模式 - 原型模式(Prototype)
设计模式·原型模式