目錄
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()
方法來克隆原型對象,得到一個新的對象。最后,我們分別展示原型對象和克隆對象的信息。