黑龙江住房和城乡建设局网站,长沙网站开发推荐,宁波妇科医生,饿了吗网站建设思路目录
1、原型模式的含义
2、C实现原型模式的简单实例 1、原型模式的含义
通过复制现有对象来创建新对象#xff0c;而无需依赖于显式的构造函数或工厂方法#xff0c;同时又能保证性能。 The prototype pattern is a creational design pattern in software development. …目录
1、原型模式的含义
2、C实现原型模式的简单实例 1、原型模式的含义
通过复制现有对象来创建新对象而无需依赖于显式的构造函数或工厂方法同时又能保证性能。 The prototype pattern is a creational design pattern in software development. It is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used to: avoid subclasses of an object creator in the client application, like the factory method pattern does. Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype. 使用原型实例指定将要创建的对象类型通过复制这个实例创建新的对象。 2、C实现原型模式的简单实例 #include iostream
#include string// 抽象原型类
class Prototype {
public:virtual Prototype* clone() const 0;virtual void show() const 0;
};// 具体原型类
class ConcretePrototype : public Prototype {
public:ConcretePrototype(const std::string name) : m_name(name) {}Prototype* clone() const override {return new ConcretePrototype(*this);}void show() const override {std::cout ConcretePrototype: m_name std::endl;}private:std::string m_name;
};int main() {// 创建原型对象Prototype* prototype new ConcretePrototype(Prototype);// 克隆原型对象Prototype* clone prototype-clone();// 展示原型和克隆对象prototype-show();clone-show();delete prototype;delete clone;return 0;
}在上述示例中我们定义了一个抽象原型类Prototype其中包含了两个纯虚函数clone()用于克隆对象show()用于展示对象。然后我们实现了具体的原型类ConcretePrototype它继承自抽象原型类并实现了抽象原型类中的纯虚函数。
在主函数中我们首先创建一个原型对象ConcretePrototype然后通过调用clone()方法来克隆原型对象得到一个新的对象。最后我们分别展示原型对象和克隆对象的信息。