原型模式(Prototype),是原型实例制定创建对象的种类,并且通过拷贝这些原型创建新的对象。
原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需知道任何创建的细节。
基本的原型模式实现代码
//基本的原型模式代码
//原型类
class Prototype
{
public:
int id1;
int id2;
public:
Prototype(){}
Prototype(int id1,int id2)
{
this->id1 = id1;
this->id2 = id2;
}
virtual Prototype *clone(){return NULL;}
};
//具体原型类,只克隆id1
class ConcretePrototype1 : public Prototype
{
public:
ConcretePrototype1(){}
ConcretePrototype1(int id1,int id2)
{
this->id1 = id1;
this->id2 = id2;
}
public:
//创建当前对象的拷贝。方法是创建一个新对象,如果当前对象中只有内置数据类型或者对象类型,而没有指针类型或者引用类型(针对非内置对象,如自己创建的类)。那么直接按位或者利用赋值构造函数进行浅拷贝即可。
//如果当前对象中有指针类型或者引用类型,则要判断是进行浅拷贝还是深拷贝,即判断是否使用不同的指针类型变量或者引用变量指向同一对象(同一块内存空间)。
Prototype *clone()
{
Prototype *temp = new Prototype();
temp->id1 = this->id1;
return temp;
}
};
//具体原型类,克隆id2
class ConcretePrototype2 : public Prototype
{
public:
ConcretePrototype2(){}
ConcretePrototype2(int id1,int id2)
{
this->id1 = id1;
this->id2 = id2;
}
public:
Prototype *clone()
{
Prototype *temp = new Prototype();
temp->id2 = this->id2;
return temp;
}
};
//客户端
int main()
{
Prototype *p1 = new ConcretePrototype1(1,2);
ConcretePrototype1 *c1 = (ConcretePrototype1 *)p1->clone();
Prototype *p2 = new ConcretePrototype2(1,2);
ConcretePrototype2 *c2 = (ConcretePrototype2 *)p2->clone();
return 1;
}
原型模式例子,拷贝简历
#include <string>
#include <iostream>
using namespace std;
//一个复制简历的程序
//工作经历
class WorkExperience
{
public:
string workDate;
string company;
public:
WorkExperience(string workDate,string company){this->company = company;this->workDate = workDate;}
};
//原型
class Prototype
{
public:
Prototype(){}
virtual Prototype *clone(){return NULL;}
};
class Resume : public Prototype
{
public:
string name;
string sex;
int age;
WorkExperience *work;
public:
Resume()
{
name = "";
sex = "";
age = 0;
work = NULL;
}
Prototype *clone()
{
Resume *temp = new Resume();
temp->name = this->name;
temp->sex = this->sex;
temp->age = this->age;
//浅拷贝
//temp->work = this->work;
//深拷贝
temp->work = new WorkExperience(work->company,work->workDate);
return (Prototype *)temp;
}
};
int main()
{
Resume temp;
temp.work = new WorkExperience("西安交通大学","2014-7-23");
Resume *c1 = (Resume *)temp.clone();
Resume *c2 = (Resume *)temp.clone();
return 1;
}