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;
}
相关推荐
chxii1 天前
4.6js面向对象
原型模式
Hanson Huang4 天前
23种设计模式-原型(Prototype)设计模式
设计模式·原型模式
诺亚凹凸曼5 天前
23种设计模式-创建型模式-原型
设计模式·原型模式
严文文-Chris5 天前
【spring对bean Singleton和Prototype的管理流程】
spring·单例模式·原型模式
东东__net5 天前
01_JavaScript
开发语言·javascript·原型模式
熊大如如8 天前
JavaScript 继承方式总结
开发语言·javascript·原型模式
搞不懂语言的程序员10 天前
原型模式详解
原型模式
小九没绝活12 天前
设计模式-原型模式
java·设计模式·原型模式
海盗强12 天前
prototype和proto的区别
开发语言·javascript·原型模式
Antonio91513 天前
【Q&A】原型模式在Qt有哪些应用?
开发语言·qt·原型模式