原型模式(Prototype)
Definition:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。通俗来讲,从一个对象创建另外一个可定制的对象,不需要知道任何创建的细节。
#include <iostream> #include <string> using namespace std; /* Prototype abstract Class */ class Prototype { public: virtual Prototype* clone() = 0; virtual void display() = 0; }; /* 原型模式类的实现 */ class Resume: public Prototype { public: Resume(string name, int id): m_name(name), m_id(id) {} Resume(const Resume &rm); void display(); Prototype* clone(); private: string m_name; int m_id; }; //Important, copy construct function Resume::Resume(const Resume &rm) { this->m_id = rm.m_id; this->m_name = rm.m_name; } void Resume::display() { cout<<"my id is "<<this->m_id<<", my name is "<<this->m_name<<endl; } //Important, clone function Prototype* Resume::clone() { return new Resume(*this); } /* 测试 */ void main() { Prototype* r1 = new Resume("zhao", 1); Prototype* r2 = r1->clone(); Prototype* r3 = r2->clone(); r1->display(); r2->display(); r3->display(); delete r1; delete r2; delete r3; system("pause"); } /* Result my id is 1, my name is zhao my id is 1, my name is zhao my id is 1, my name is zhao */
Tips:
支持复制(clone function)当前对象的模式.
重要函数 拷贝构造函数和clone函数