C++ Prototype 模式实现

内容目录

Prototype模式允许我们通过克隆现有对象来创建新对象,而无需依赖其具体类。这样做可以避免与对象复杂的构造过程相关的代价,同时还能确保新对象的状态独立于原始对象。

简单实现:

#include <iostream>
#include <string>

// Prototype基类
class Prototype {
public:
    virtual Prototype* clone() = 0;
    virtual void printInfo() = 0;
};

// 具体原型类
class ConcretePrototype : public Prototype {
private:
    std::string data;

public:
    ConcretePrototype(std::string data) : data(data) {}

    Prototype* clone() override {
        return new ConcretePrototype(data);
    }

    void printInfo() override {
        std::cout << "Data: " << data << std::endl;
    }
};

int main() {
    ConcretePrototype* prototype = new ConcretePrototype("Original Data");
    Prototype* clonedPrototype = prototype->clone();

    prototype->printInfo();
    clonedPrototype->printInfo();

    delete prototype;
    delete clonedPrototype;

    return 0;
}

加入管理器:

#include <iostream>
#include <string>
#include <unordered_map>

// 原型基类
class Prototype {
public:
    virtual Prototype* clone() = 0;
    virtual void printInfo() = 0;
};

// 具体原型类
class ConcretePrototype : public Prototype {
private:
    std::string data;

public:
    ConcretePrototype(std::string data) : data(data) {}

    Prototype* clone() override {
        return new ConcretePrototype(data);
    }

    void printInfo() override {
        std::cout << "Data: " << data << std::endl;
    }
};

// 原型管理类
class PrototypeManager {
private:
    std::unordered_map<std::string, Prototype*> prototypes;

public:
    Prototype* getPrototype(std::string key) {
        return prototypes[key]->clone();
    }

    void addPrototype(std::string key, Prototype* prototype) {
        prototypes[key] = prototype;
    }
};

int main() {
    PrototypeManager manager;
    ConcretePrototype* prototype = new ConcretePrototype("Prototype Data");
    manager.addPrototype("Prototype", prototype);

    Prototype* clonedPrototype = manager.getPrototype("Prototype");
    clonedPrototype->printInfo();

    delete prototype;
    delete clonedPrototype;

    return 0;
}
打赏作者