C++设计模式学习笔记六:原型模式

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值