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;
}
相关推荐
灰海4 天前
原型与原型链到底是什么?
开发语言·前端·javascript·es6·原型模式·原生js
找不到、了5 天前
Spring的Bean原型模式下的使用
java·spring·原型模式
面朝大海,春不暖,花不开7 天前
使用 Python 实现 ETL 流程:从文本文件提取到数据处理的全面指南
python·etl·原型模式
Shartin8 天前
CPT208-Human-Centric Computing: Prototype Design Optimization原型设计优化
开发语言·javascript·原型模式
N_NAN_N10 天前
类图+案例+代码详解:软件设计模式----原型模式
java·设计模式·原型模式
铛铛啦啦啦10 天前
“对象创建”模式之原型模式
设计模式·原型模式
D.eL22 天前
深入解析原型模式:从理论到实践的全方位指南
java·设计模式·原型模式
永生辉皇22 天前
JS红宝书笔记 8.4 类
javascript·笔记·原型模式
胡侃有料22 天前
【设计模式】6.原型模式
设计模式·原型模式
OpenC++22 天前
【C++】原型模式
开发语言·c++·设计模式·原型模式