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;
}
相关推荐
询问QQ:180809512 天前
永磁同步电机参数辨识那些事儿
原型模式
小白勇闯网安圈2 天前
wife_wife、题目名称-文件包含、FlatScience
javascript·python·网络安全·web·原型模式
还是大剑师兰特3 天前
ES6 class相关内容详解
es6·原型模式·大剑师
ZouZou老师3 天前
C++设计模式之原型模式:以家具生产为例
c++·设计模式·原型模式
San30.4 天前
从原型链到“圣杯模式”:JavaScript 继承方案的演进与终极解法
开发语言·javascript·原型模式
AAA阿giao5 天前
深入理解 JavaScript 中的面向对象编程(OOP):从构造函数到原型继承
开发语言·前端·javascript·原型·继承·原型模式·原型链
勇气要爆发7 天前
物种起源—JavaScript原型链详解
开发语言·javascript·原型模式
AAA阿giao7 天前
JavaScript 原型与原型链:从零到精通的深度解析
前端·javascript·原型·原型模式·prototype·原型链
chilavert3188 天前
技术演进中的开发沉思-225 Prototype.js 框架
开发语言·javascript·原型模式
雨中飘荡的记忆8 天前
设计模式之原型模式详解
设计模式·原型模式