原型模式是用原型实例指定创建兑现的种类,并且通过拷贝这些原型创建新的对象。原型模式说白了其实就是有一个把自己拷贝一下的方法。该模式很好理解,该模式独特地方不是类与类之间的关系,更多的是从语义上理解,只是实现了一个接口而已。
其UML图如下:
示例代码如下:
// PrototypeModel.h文件 #pragma once #include <iostream> #include <string> // 原型类 class Prototype { public: virtual Prototype * Clone() = 0; }; // class ConcretePrototype_0 : public Prototype { public: ConcretePrototype_0(std::string name) { m_strTypeName = name; } virtual Prototype * Clone() { ConcretePrototype_0 *p = new ConcretePrototype_0(m_strTypeName); *p = *this; return p; } void Show() { std::cout << m_strTypeName << std::endl; } private: std::string m_strTypeName; }; class ConcretePrototype_1 : public Prototype { public: ConcretePrototype_1(std::string name) { m_strTypeName = name; } virtual Prototype * Clone() { ConcretePrototype_1 *p = new ConcretePrototype_1(m_strTypeName); *p = *this; return p; } void Show() { std::cout << m_strTypeName << std::endl; } private: std::string m_strTypeName; };测试代码如下:
#include <iostream> #include "PrototypeModel.h" int main() { using namespace std; ConcretePrototype_0 * p1 = new ConcretePrototype_0("A"); ConcretePrototype_1 * p2 = (ConcretePrototype_1 *)(p1->Clone()); p1->Show(); p2->Show(); delete p1; delete p2; getchar(); return 0; }测试结果如下图: