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;
}
相关推荐
方见华Richard2 天前
世毫九《认知几何学修订版:从离散概念网络到认知拓扑动力学》
人工智能·经验分享·交互·原型模式·空间计算
方见华Richard2 天前
自指系统的安全本体论:论内生安全性的哲学基础与形式化路径
人工智能·经验分享·交互·学习方法·原型模式
xianyinsuifeng2 天前
RAG + Code Analysis 的标准路线
数据仓库·自动化·云计算·原型模式·aws
Beginner x_u4 天前
JavaScript 原型、原型链与原型继承的核心机制解析
开发语言·javascript·原型模式·原型原型链
方见华Richard5 天前
递归对抗引擎(RAE)核心极简实现框架
人工智能·交互·学习方法·原型模式·空间计算
方见华Richard5 天前
递归对抗引擎RAE V2.0(多智能体分布式对抗版)
人工智能·经验分享·交互·学习方法·原型模式
方见华Richard5 天前
递归对抗引擎RAE V3.0(碳硅共生版)
人工智能·经验分享·学习方法·原型模式·空间计算
懵萌长颈鹿6 天前
原型模式 (Prototype Pattern)
原型模式
2601_949480067 天前
Flutter for OpenHarmony音乐播放器App实战:定时关闭实现
javascript·flutter·原型模式
方见华Richard8 天前
解构对话本体论:实验设计与认知重构
人工智能·交互·学习方法·原型模式·空间计算