设计模式总篇-原型模式

//克隆
#define __CRT_SECURE_NO_WARNINGS

/*
@作者:莫忘输赢
@时间:
2020/2/10 14:36
@版本:v1

@原型模式
@作用
用于备份

*/



#include<iostream>
#include<vector>
#include<string>

//#include<vld.h>

//using namespace std;
//原型模式 - 基类
class ProtoType
{
private:
	std::string m_strName;
public:
	ProtoType(std::string strName){ m_strName = strName; }
	ProtoType(){ m_strName = " ";};
	void show()
	{
		std::cout << m_strName << std::endl;
	}
	virtual ProtoType *Clone( ) = 0;
};
//class CProtoType1
class CProtoType1 : public ProtoType
{
public:
	CProtoType1(std::string strName) : ProtoType(strName){ }
	CProtoType1(){ }

	virtual ProtoType* Clone()
	{
		CProtoType1 *p = new CProtoType1();
		*p = *this;
		return p;
	}
};
//class CProtoType2
class CProtoType2 : public ProtoType
{
public:
	CProtoType2(std::string strName) : ProtoType(strName){ }
	CProtoType2(){ }

	virtual ProtoType* Clone()
	{
		CProtoType2 *p = new CProtoType2( );
		*p = *this;
		return p;
	}
};
int main(int argc, char **argv)
{
	CProtoType1 *CP1 = new CProtoType1("张三");
	CProtoType2 *CP2 = (CProtoType2*)CP1->Clone();


	CP1->show();
	CP2->show();

	delete CP1;
	CP1 = nullptr;
	delete CP2;
	CP2 = nullptr;

	return 0;
}
发布了141 篇原创文章 · 获赞 1 · 访问量 5323

猜你喜欢

转载自blog.csdn.net/wjl18270365476/article/details/104410607