← 返回博客列表

模式特点

用原型实例指定创建对象的种类,并且通过拷贝这些原型来创建新对象。原型模式通过克隆已有对象来避免重复初始化。

类图

类图

应用场景

示例代码(C++)

// 抽象原型
class Monster {
public:
    virtual Monster* clone() = 0;
    virtual ~Monster() = default;
    std::string name; int hp; int attack;
};

// 具体原型
class Goblin : public Monster {
public:
    Goblin(std::string n, int h, int a) { name = n; hp = h; attack = a; }

    // 深拷贝克隆
    Monster* clone() override {
        return new Goblin(*this);
    }
};

// 使用原型注册表
class MonsterRegistry {
    std::map<std::string, Monster*> m_prototypes;
public:
    void registerMonster(const std::string& key, Monster* proto) {
        m_prototypes[key] = proto;
    }
    Monster* createMonster(const std::string& key) {
        return m_prototypes[key]->clone();
    }
};

MonsterRegistry registry;
registry.registerMonster("goblin", new Goblin("哥布林", 100, 15));
Monster* m1 = registry.createMonster("goblin");  // 克隆出新对象