原型模式通过克隆现有对象创建新对象,避免复杂构造。定义抽象基类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) {}
<font color="#006400"><strong>// 实现克隆方法</strong></font>
Prototype* clone() <font color="#0000FF"><strong>const override</strong></font> {
<font color="#0000FF"><strong>return</strong></font> <font color="#0000FF"><strong>new</strong></font> ConcretePrototype(*<font color="#0000FF"><strong>this</strong></font>);
}
<font color="#0000FF"><strong>void</strong></font> show() <font color="#0000FF"><strong>const</strong></font> {
std::cout << "Value: " << value << ", Data: " << data << "\n";
}};
立即学习“C++免费学习笔记(深入)”;
为了更方便地管理和创建原型对象,可以引入一个原型注册表,按名称存储和获取原型实例。
class PrototypeManager { private: std::unordered_map<:string prototype> prototypes;public:void addPrototype(const std::string& name, Prototype* proto) { if (prototypes.find(name) == prototypes.end()) { prototypes[name] = proto; } }
Prototype* create(<font color="#0000FF"><strong>const</strong></font> std::string& name) {
<font color="#0000FF"><strong>auto</strong></font> it = prototypes.find(name);
<font color="#0000FF"><strong>if</strong></font> (it != prototypes.end()) {
<font color="#0000FF"><strong>return</strong></font> it->second->clone();
}
<font color="#0000FF"><strong>return</strong></font> nullptr;
}
~PrototypeManager() {
<font color="#0000FF"><strong>for</strong></font> (<font color="#0000FF"><strong>auto</strong></font>& pair : prototypes) {
<font color="#0000FF"><strong>delete</strong></font> pair.second;
}
}};
立即学习“C++免费学习笔记(深入)”;
使用原型模式创建对象:
int main() { PrototypeManager manager; manager.addPrototype("example", new ConcretePrototype(42, "sample"));Prototype* obj1 = manager.create("example");
Prototype* obj2 = manager.create("example");
<font color="#0000FF"><strong>static_cast</strong></font><ConcretePrototype*>(obj1)->show(); <font color="#006400"><strong>// 输出相同内容</strong></font>
<font color="#0000FF"><strong>static_cast</strong></font><ConcretePrototype*>(obj2)->show();
<font color="#0000FF"><strong>delete</strong></font> obj1;
<font color="#0000FF"><strong>delete</strong></font> obj2;
<font color="#0000FF"><strong>return</strong></font> 0;}
基本上就这些。关键在于 clone 方法的实现要保证对象状态完整复制,注意深拷贝问题。如果成员包含指针或资源,需手动实现拷贝构造函数以避免浅拷贝带来的问题。
以上就是C++怎么实现一个原型模式_C++通过复制现有实例来创建新对象的设计模式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号