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;
}
相关推荐
likerhood7 天前
设计模式:原型模式(Prototype Pattern)java版本
java·设计模式·原型模式
geovindu11 天前
go: Prototype Pattern
开发语言·设计模式·golang·原型模式
幸运小圣12 天前
Array.prototype.reduce 全面解析【JS方法】
开发语言·javascript·原型模式
两年半的个人练习生^_^14 天前
每日一学:设计模式之原型模式
java·开发语言·设计模式·原型模式
UXbot15 天前
如何用 AI 快速生成完整的移动端 UI 界面:从描述到交付的实操教程
前端·ui·交互·ai编程·原型模式
神の愛16 天前
js的深拷贝和浅拷贝?啥情况讲解下??底层堆栈空间??object.prototype.toString.call(),还有bind,的具体使用?
前端·javascript·原型模式
W.A委员会17 天前
JS原型链详解
开发语言·javascript·原型模式
Rsun0455117 天前
5、Java 原型模式从入门到实战
java·开发语言·原型模式
码云数智-大飞19 天前
JavaScript 原型链与继承机制:从底层原理到 ES6 Class 的本质
原型模式
妙蛙种子31120 天前
【Java设计模式 | 创建者模式】 原型模式
java·开发语言·后端·设计模式·原型模式