解析设计模式中的Prototype原型模式及在C++中的使用
原型模式的意图是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。 适用性 关于这个模式,突然想到了小时候看的《西游记》,齐天大圣孙悟空再发飙的时候可以通过自己头上的 3 根毛立马复制出来成千上万的孙悟空,对付小妖怪很管用(数量最重要)。 原型模式也正是提供了自我复制的功能,就是说新对象的创建可以通过已有对象进行创建。在 C++中拷贝构造函数(Copy Constructor)曾经是很对程序员的噩梦,浅层拷贝和深层拷贝的魔魇也是很多程序员在面试时候的快餐和系统崩溃时候的根源之一。 结构图: 原型模式提供了一个通过已存在对象进行新对象创建的接口(Clone),Clone()实现和具体的实现语言相关,在 C++中我们将通过拷贝构造函数实现之。 例子 #include <iostream> using namespace std; class Student { protected: int id; char name[10]; public: Student() { } ~Student() { cout<<"Desconstuct...."<<endl; } virtual Student *Clone() {} virtual void Show() { } }; class StudentTypeA:public Student { public: StudentTypeA(const char *name_input) { strcpy(name,name_input); this->id = 0; cout<<"Construction....."<<endl; } StudentTypeA(const StudentTypeA&other) { cout<<"Copy Construction..."<<endl; this->id = other.id; this->id ++; strcpy(this->name,other.name); } virtual StudentTypeA *Clone() { StudentTypeA *tmp = new StudentTypeA(*this); return tmp; } void Show() { cout<<"Student id == "<< id << " name == "<< name <<endl; } ~StudentTypeA() { cout<<"Deconstruction StudentTypeA"<<endl; } }; int main() { Student *student1 = new StudentTypeA("fulima"); Student *student2 = student1->Clone(); Student *student3 = student2->Clone(); student1->Show(); student2->Show(); student3->Show(); return 0; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |