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;
}
相关推荐
叶总没有会15 小时前
5.1知识库概念进阶
java·人工智能·spring·阿里云·ai·原型模式
lincats21 小时前
智能体工程 vs 软件工程:计算机系那套课程,还能适应 AI 时代吗?
人工智能·软件工程·原型模式·vibecoding·claudecode·grillme
ltqvibe5 天前
数据中台为什么走不通——本体语义给出的替代路径
人工智能·原型模式·本体语义平台
啦啦啦啦啦zzzz7 天前
设计模式:原型模式
c++·设计模式·原型模式
choumin14 天前
创建型模式——原型模式
c++·设计模式·原型模式·创建型模式
我登哥MVP1 个月前
走进 Gang of Four 设计模式:访问者模式
java·设计模式·访问者模式·原型模式
学究天人1 个月前
数学公理体系大全:第五章 序数与基数理论:超限算术与集合的大小
人工智能·线性代数·算法·机器学习·数学建模·原型模式
学究天人1 个月前
数学公理体系大全:第六章 选择公理的等价形式及证明
人工智能·线性代数·算法·机器学习·数学建模·概率论·原型模式
学究天人1 个月前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(补充卷9)
人工智能·线性代数·算法·数学建模·动态规划·原型模式·抽象代数
geovindu1 个月前
CSharp: Prototype Pattern
开发语言·后端·设计模式·.net·原型模式·创建型模式