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;
}
相关推荐
江畔柳前堤2 天前
具身智能全景深度指南(2026年9月版):从“会聊天的AI“到“能干活的机器“
大数据·javascript·图像处理·人工智能·分布式·智慧城市·原型模式
神奇霸王龙7 天前
Codex MCP GA 实测:Qwen / GLM / Kimi / DeepSeek / MiniMax 调度 Codex 沙箱的真实成本
人工智能·ai·agent·ai编程·原型模式·mcp
葡萄城技术团队9 天前
如何通过 JSON 数据源 / Web API 快速构建轻量级报表(Report)?
前端·json·原型模式
Leo.yuan9 天前
2026国内数据治理平台选型指南:从ETL到数据质量的一体化路径
原型模式
一个游离的指针22 天前
JS中的对象的相关概念
开发语言·javascript·原型模式
码哥DFS24 天前
构造函数、实例对象、对象原型 ----三者关系
开发语言·javascript·原型模式
lincats1 个月前
AI Agent 工程化六层架构:从 Prompt 到 Production
人工智能·架构·prompt·知识图谱·原型模式·vibecoding·grillme
叶总没有会1 个月前
5.1知识库概念进阶
java·人工智能·spring·阿里云·ai·原型模式
lincats1 个月前
智能体工程 vs 软件工程:计算机系那套课程,还能适应 AI 时代吗?
人工智能·软件工程·原型模式·vibecoding·claudecode·grillme
ltqvibe1 个月前
数据中台为什么走不通——本体语义给出的替代路径
人工智能·原型模式·本体语义平台