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;
}
相关推荐
勤奋的知更鸟1 小时前
Java编程之原型模式
java·开发语言·原型模式
じ☆ve 清风°2 天前
JavaScript 原型与原型链:深入理解 __proto__ 和 prototype 的由来与关系
开发语言·javascript·原型模式
产品设计大观2 天前
拆解实战案例:电商ERP管理系统从需求到原型全流程设计
产品经理·原型模式·erp·墨刀·erp系统·原型设计·电商erp系统
_r0bin_3 天前
前端八股之JS的原型链
原型模式
将编程培养成爱好3 天前
《复制粘贴的奇迹:小明的原型工厂》
c++·设计模式·原型模式
独步炎凉的大彬4 天前
new操作符具体做了什么
开发语言·javascript·原型模式
linux-hzh9 天前
设计模式之原型模式
设计模式·原型模式
on the way 12310 天前
创建型设计模式之Prototype(原型)
设计模式·原型模式
秋田君12 天前
深入理解JavaScript设计模式之原型模式
javascript·设计模式·原型模式
qqxhb15 天前
零基础设计模式——第二部分:创建型模式 - 原型模式
设计模式·原型模式·浅拷贝·深拷贝