原型模式,用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。原型模式其实就是从一个对象再创建另外一个可定制的对象,而且不需要知道任何创建的细节。在C++里,可通过拷贝构造函数实现原型模式,或者实现赋值运算符也能达到相同的目的,下面是原型模式的UML图。
代码如下:
#ifndef __WORKEXPERIENCE_H
#define __WORKEXPERIENCE_H
#include <string.h>
class WorkExperience
{
public:
char m_szWorkDate[256];
char m_szWorkCompany[256];
public:
WorkExperience()
{
memset(m_szWorkDate, 0, 256);
memset(m_szWorkCompany, 0, 256);
}
~WorkExperience() {}
WorkExperience(const WorkExperience& we)
{
memcpy(m_szWorkDate, we.m_szWorkDate, 256);
memcpy(m_szWorkCompany, we.m_szWorkCompany, 256);
}
WorkExperience& operator=(const WorkExperience& other)
{
if (this == &other )
return *this;
memcpy(m_szWorkDate, other.m_szWorkDate, 256);
memcpy(m_szWorkCompany, other.m_szWorkCompany, 256);
return *this;
}
};
#endif // !__WORKEXPERIENCE_H
#ifndef __RESUME_H
#define __RESUME_H
#include "WorkExperience.h"
#include "stdio.h"
class Resume
{
private:
WorkExperience we;
char m_szName[256];
char m_szSex[256];
char m_szAge[256];
public:
Resume(char* name)
{
InitResume();
if (NULL == name)
{
memcpy(m_szName, "Default", 256);
return;
}
memcpy(m_szName, name, 256);
}
~Resume() {}
Resume(const Resume& other)
{
InitResume();
memcpy(m_szName, other.m_szName, 256);
memcpy(m_szSex, other.m_szSex, 256);
memcpy(m_szAge, other.m_szAge, 256);
we = other.we;
}
Resume& operator=(const Resume& other)
{
if (this == &other)
return *this;
memcpy(m_szName, other.m_szName, 256);
memcpy(m_szSex, other.m_szSex, 256);
memcpy(m_szAge, other.m_szAge, 256);
we = other.we;
}
void SetPersonalInfo(char* sex, char * age)
{
if ( ( NULL == sex) )
{
memcpy(m_szSex, "M", 256);
}
if ((NULL == age))
{
memcpy(m_szSex, "18", 256);
}
memcpy(m_szSex, sex, 256);
memcpy(m_szAge, age, 256);
}
void SetWorkExperience(char* workDate, char* company)
{
memcpy(we.m_szWorkDate, workDate, 256);
memcpy(we.m_szWorkCompany, company, 256);
}
void Display()
{
printf("%s %s %s \n", m_szName, m_szSex, m_szAge);
printf("工作经历:%s %s\n", we.m_szWorkDate, we.m_szWorkCompany);
}
void InitResume()
{
memset(m_szName, 0, 256);
memset(m_szSex, 0, 256);
memset(m_szAge, 0, 256);
}
};
#endif // !__RESUME_H
//客户端代码
#include "Resume.h"
#include <tchar.h>
int _tmain(int argc, TCHAR* argv[])
{
Resume xResume ("Mr.Wang");
xResume.SetPersonalInfo("M", "28");
xResume.SetWorkExperience("1998-2000", "xx公司");
Resume yResume(xResume);
yResume.SetWorkExperience("1998-2006", "yy企业");
Resume zResume(xResume);
zResume.SetPersonalInfo("M", "24");
zResume.SetWorkExperience("1998-2003", "zz企业");
xResume.Display();
yResume.Display();
zResume.Display();
}
运行结果: