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;
}
相关推荐
努力也学不会java5 天前
【设计模式】 原型模式
java·设计模式·原型模式
Meteors.6 天前
23种设计模式——原型模式 (Prototype Pattern)详解
设计模式·原型模式
女生也可以敲代码9 天前
JavaScript闭包、原型链、事件循环,一文彻底讲明白(小白也能懂)
开发语言·原型模式
给月亮点灯|9 天前
Vue基础知识-重要的内置关系:vc实例.__proto__.__proto__ === Vue.prototype
前端·vue.js·原型模式
心前阳光9 天前
Unity通过Object学习原型模式
学习·unity·原型模式
小凯 ོ16 天前
实战原型模式案例
java·后端·设计模式·原型模式
JuneXcy20 天前
28.原型
开发语言·javascript·原型模式
楚禾Noah21 天前
【设计模式实战】原型模式 + 工厂模式:AI Agent 配置中心
人工智能·设计模式·原型模式
找不到、了1 个月前
Java设计模式之《原型模式》--深、浅copy
java·设计模式·原型模式
阿维的博客日记1 个月前
@Scope(value = WebApplicationContext.SCOPE_REQUEST)和@Scope(“prototype“)区别
原型模式