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;
}
相关推荐
white-persist3 天前
SQL 注入详解:从原理到实战
前端·网络·数据库·sql·安全·web安全·原型模式
white-persist3 天前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
魔云连洲5 天前
深入解析:Object.prototype.toString.call() 的工作原理与实战应用
前端·javascript·原型模式
white-persist7 天前
Burp Suite模拟器抓包全攻略
前端·网络·安全·web安全·notepad++·原型模式
青草地溪水旁7 天前
第五章:原型模式 - 克隆大法的大师
c++·设计模式·原型模式
white-persist7 天前
【burp手机真机抓包】Burp Suite 在真机(Android and IOS)抓包手机APP + 微信小程序详细教程
android·前端·ios·智能手机·微信小程序·小程序·原型模式
XiaoLeisj12 天前
【SpringAI】第四弹:深入解析 Rag 检索增强工作流程、最佳实践和调优
阿里云·原型模式·rag·spring ai·灵积大模型
CoderIsArt13 天前
四种对象型创建模式:抽象工厂、 build模式、原型ProtoType与单例模式
单例模式·原型模式
Misnearch14 天前
原型模式了解
原型模式
charlie11451419116 天前
精读《C++20设计模式》——创造型设计模式:原型模式
设计模式·程序设计·原型模式·c++20