原型模式通过克隆现有对象创建新对象,避免复杂构造。定义抽象基类Prototype,声明纯虚clone方法;具体类如ConcretePrototype实现clone,返回自身副本;可选PrototypeManager管理原型实例,按名创建对象。

原型模式是一种创建型设计模式,它通过复制已有的实例来创建新的对象,而不是通过 new 关键字重新构造。在 C++ 中实现原型模式的关键是定义一个抽象接口,让具体类自己实现克隆方法,从而实现动态对象创建和避免复杂的构造过程。
定义原型接口
首先,定义一个抽象基类,声明一个纯虚的 clone 接口。所有可被复制的对象都继承这个接口。
class Prototype { public:virtual ~Prototype() = default; virtual Prototype* clone() const = 0; };实现具体原型类
每个具体类需要重写 clone 方法,返回自身的一个副本。这里可以使用拷贝构造函数来确保深拷贝或浅拷贝的正确性。
class ConcretePrototype : public Prototype { private:int value; std::string data;public: ConcretePrototype(int v, const std::string& d) : value(v), data(d) {}
// 实现克隆方法
Prototype* clone() const override {
return new ConcretePrototype(*this);
}
void show() const {
std::cout << "Value: " << value << ", Data: " << data << "\n";
}};
立即学习“C++免费学习笔记(深入)”;
使用原型管理器(可选)
为了更方便地管理和创建原型对象,可以引入一个原型注册表,按名称存储和获取原型实例。
public:void addPrototype(const std::string& name, Prototype* proto) { if (prototypes.find(name) == prototypes.end()) { prototypes[name] = proto; } }
Prototype* create(const std::string& name) {
auto it = prototypes.find(name);
if (it != prototypes.end()) {
return it->second->clone();
}
return nullptr;
}
~PrototypeManager() {
for (auto& pair : prototypes) {
delete pair.second;
}
}};
立即学习“C++免费学习笔记(深入)”;
示例用法
使用原型模式创建对象:
int main() { PrototypeManager manager; manager.addPrototype("example", new ConcretePrototype(42, "sample"));Prototype* obj1 = manager.create("example");
Prototype* obj2 = manager.create("example");
static_cast(obj1)->show(); // 输出相同内容
static_cast(obj2)->show();
delete obj1;
delete obj2;
return 0; }
基本上就这些。关键在于 clone 方法的实现要保证对象状态完整复制,注意深拷贝问题。如果成员包含指针或资源,需手动实现拷贝构造函数以避免浅拷贝带来的问题。









