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;
}
相关推荐
秋名RG1 天前
深入理解设计模式之原型模式(Prototype Pattern)
设计模式·原型模式
长袖格子衫2 天前
第五节:对象与原型链:JavaScript 的“类”与“继承”
开发语言·javascript·原型模式
常某某的好奇心4 天前
原型模式(Prototype Pattern)
原型模式
牛奶咖啡134 天前
学习设计模式《八》——原型模式
学习·设计模式·原型模式·浅度克隆·深度克隆·c#的克隆·原型管理器
帝锦_li10 天前
Java进阶--设计模式
观察者模式·单例模式·代理模式·抽象工厂模式·适配器模式·原型模式
hyyyyy!14 天前
《从分遗产说起:JS 原型与继承详解》
前端·javascript·原型模式
Frankabcdefgh15 天前
前端面试 js
开发语言·javascript·原型模式
麓殇⊙16 天前
设计模式-- 原型模式详解
设计模式·原型模式
智想天开16 天前
11.原型模式:思考与解读
设计模式·原型模式
碎梦归途20 天前
23种设计模式-创建型模式之原型模式(Java版本)
java·开发语言·jvm·设计模式·原型模式