1、原型模式:用原型实例指定对象的种类,并且通过拷贝这些原型创建新的对象。
原型模式就是从一个对象创建另一个可定制的对象,而且不需要知道任何创建的细节。
除了需关注原型设计模式的特点和使用场景外,还需关注大话设计模式中所说的深拷贝和浅拷贝。他们之间的区别可以细看下面的C++代码。
2、类图:

3、C++代码:
// PrototypePattern.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <iostream>
using namespace std;
class IClone
{
public:
virtual void* Clone() = 0;
};
class WorkExperience : IClone
{
public:
std::string m_sWorkDate;
std::string m_sCompany;
void* Clone()
{
WorkExperience* we = new WorkExperience();
we->m_sWorkDate = m_sWorkDate;
we->m_sCompany = m_sCompany;
return we;
}
};
class Resume : IClone
{
public:
Resume(){}
~Resume(){ delete m_pWe; }
Resume(std::string strName)
{
m_sName = strName;
m_pWe = new WorkExperience();
}
Resume(WorkExperience* we)
{
//m_pWe = we;
m_pWe = (WorkExperience*)we->Clone();
}
void SetPersonalInfo(std::string strAge, std::string strSex)
{
m_sAge = strAge;
m_sSex = strSex;
}
void SetWorkExperience(std::string strDate, std::string strCompany)
{
m_pWe->m_sWorkDate = strDate;
m_pWe->m_sCompany = strCompany;
}
void DisplayInfo()
{
cout<<m_sName<<" "<<m_sSex<<" "<<m_sAge<<endl;
cout<<"工作经历:"<<m_pWe->m_sWorkDate<<" "<<m_pWe->m_sCompany<<endl;
}
void* Clone()
{
Resume* res = new Resume(this->m_pWe);
res->m_sName = m_sName;
res->m_sSex = m_sSex;
res->m_sAge = m_sAge;
return res;
}
private:
WorkExperience* m_pWe;
std::string m_sName;
std::string m_sAge;
std::string m_sSex;
};
int _tmain(int argc, _TCHAR* argv[])
{
Resume* res = new Resume("大鸟");
res->SetPersonalInfo("29", "男");
res->SetWorkExperience("2008-2011", "XX");
Resume* res1 = (Resume*)res->Clone();
res1->SetWorkExperience("2009-2012", "YY");
Resume* res2 = (Resume*)res->Clone();
res2->SetWorkExperience("2009-2012", "ZZ");
res->DisplayInfo();
res1->DisplayInfo();
res2->DisplayInfo();
delete res;
delete res1;
delete res2;
return 0;
}
|