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 天前
【设计模式精讲】创建型模式之原型模式(深克隆、浅克隆)
设计模式·原型模式
Samson Bruce2 天前
【创建模式-原型模式(Prototype Pattern)】
原型模式
強云3 天前
23种设计模式 - 原型模式
设计模式·原型模式
le_duoduo4 天前
原型模式详解(Java)
java·原型模式
lonelyhiker4 天前
javascript的原型链
开发语言·javascript·原型模式
新时代的弩力5 天前
Function.prototype.__proto__==Object.prototype
开发语言·javascript·原型模式
无限大.7 天前
前端知识速记—JS篇:原型与原型链
前端·javascript·原型模式
wy02_7 天前
【设计模式】 建造者模式和原型模式
设计模式·建造者模式·原型模式
ox00809 天前
C++ 设计模式-原型模式
c++·设计模式·原型模式
码了三年又三年11 天前
面向对象中的原型
原型模式