欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

设计模式之原型模式(prototype)

程序员文章站 2022-06-13 16:04:34
...

原理:拷贝自身对象实际上就是调用的拷贝构造函数,注意事项是这里的拷贝是深拷贝,即需要拷贝指针所指的内容

#include <stdio.h>
#include <memory>
#include <iostream>

class Resume
{
public:
	virtual Resume* Clone(){return NULL;}
	virtual ~Resume(){}
protected:
	char *name;
};

class ResumeA:public Resume
{
public:
	 ResumeA(const char* str);
	 Resume* Clone();
	 ResumeA(const ResumeA& r);
	 ~ResumeA();	 
};

ResumeA::ResumeA(const char* str)
{
	if (str == NULL)
	{
		name= new char[1];
		name[0] = '\0';
	}
	else
	{
		int length = strlen(str);
		name = new char[length + 1];
		strcpy(name,str);
		name[length] = '\0';
	}
}

ResumeA::ResumeA(const ResumeA& r)
{
	int length = strlen(r.name);
	name = new char[length + 1];
	strcpy(name,r.name);

}
Resume* ResumeA::Clone()
{
	return new Resume(*this);
}

int main()
{
	Resume* pObja= new ResumeA("abc");
	Resume* pCloneObja= pObja->Clone();
	delete pObja;
	delete pCloneObja;
	return 0;
}