解析设计模式中的Prototype原型模式及在C++中的使用
解析设计模式中的Prototype原型模式及在C++中的使用
发布时间:2016-12-28 来源:查字典编辑
摘要:原型模式的意图是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。适用性当要实例化的类是在运行时刻指定时,例如,通过动态装载;...

原型模式的意图是用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

适用性

当要实例化的类是在运行时刻指定时,例如,通过动态装载;或者

为了避免创建一个与产品类层次平行的工厂类层次时;或者

当一个类的实例只能有几个不同状态组合中的一种时。建立相应数目的原型并克隆它们可能比每次用合适的状态手工实例化该类更方便一些。

关于这个模式,突然想到了小时候看的《西游记》,齐天大圣孙悟空再发飙的时候可以通过自己头上的 3 根毛立马复制出来成千上万的孙悟空,对付小妖怪很管用(数量最重要)。

原型模式也正是提供了自我复制的功能,就是说新对象的创建可以通过已有对象进行创建。在 C++中拷贝构造函数(Copy Constructor)曾经是很对程序员的噩梦,浅层拷贝和深层拷贝的魔魇也是很多程序员在面试时候的快餐和系统崩溃时候的根源之一。

结构图:

解析设计模式中的Prototype原型模式及在C++中的使用1

原型模式提供了一个通过已存在对象进行新对象创建的接口(Clone),Clone()实现和具体的实现语言相关,在 C++中我们将通过拷贝构造函数实现之。

例子

注意事项:

(1)根据原型模式的UML图可以知道,实现要依赖于抽象要不要依赖与具体

(2)拷贝构造函数是核心,而且针对c++要进行的是深拷贝

(3)克隆函数的关键就是调用拷贝构造函数

#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; }

推荐文章
猜你喜欢
附近的人在看
推荐阅读
拓展阅读
相关阅读
网友关注
最新C语言学习
热门C语言学习
编程开发子分类