原型模式(16)

原型模式

用原型指定创建对象的种类,并且通过拷贝这些原型创建新的对象
原型模式(16)_第1张图片
其关键点在于clone函数,调用clone函数来创建更多相同类型的对象

#include
#include
using namespace std;
//父类  Resume:简历
class Resume  
{  
protected:  
	char *name;//有指针类型,防止浅拷贝
public:  
	Resume() {}  
	virtual ~Resume() {}  
	virtual Resume* Clone() { return NULL; }  //关键函数
	virtual void Set(char *n) {}  
	virtual void Show() {}  
};  

class ResumeA : public Resume  
{  
public:  
	ResumeA(){}
	ResumeA(char *str);  //构造函数  
	ResumeA(const ResumeA &r); //拷贝构造函数  
	~ResumeA();              //析构函数  
	ResumeA* Clone();         //克隆,关键所在  
	void Show();             //显示内容  
};  
ResumeA::ResumeA(char *str)   
{  
	if(str == NULL) 
	{  
		name = new char[1];   
		name[0] = '\0';   
	}  
	else//切记要深拷贝,不要浅拷贝
	{  
		name = new char[strlen(str)+1];  
		strcpy(name, str);  
	}  

	//浅拷贝代码如下
	//name = str;
}  
ResumeA::~ResumeA()
{ 
	delete [] name;
}  
ResumeA::ResumeA(const ResumeA &r)
{  
	name = new char[strlen(r.name)+1];  
	strcpy(name, r.name);  
}  
ResumeA* ResumeA::Clone() 
{  
	return new ResumeA(*this); 
	//直接调用类的拷贝构造函数
	//其实也可以在本函数内自己实现拷贝构造函数的内容
	//代码如下
	/*
	ResumeA * m_sum = new ResumeA();
	if(name == NULL) 
	{  
		m_sum->name = new char[1];   
		m_sum->name[0] = '\0';   
	}  
	else//切记要深拷贝,不要浅拷贝
	{  
		m_sum->name = new char[strlen(name)+1];  
		strcpy(m_sum->name, name);  
	}  
	return m_sum;
	*/
}  
void ResumeA::Show()
{  
	cout<<"ResumeA name : "<<name<<endl;   
}  


int main()  
{  
	Resume *r1 = new ResumeA("A");  
	Resume *r2 = new ResumeA("B");  
	Resume *r3 = r1->Clone();  
	Resume *r4 = r2->Clone();  
	r1->Show(); r2->Show();  
	//删除r1,r2  
	delete r1; delete r2;     
	r1 = r2 = NULL;  
	cout<<"-----------------------"<<endl;
	//深拷贝所以对r3,r4无影响  
	r3->Show();
	r4->Show();  
	delete r3; delete r4;  
	r3 = r4 = NULL;  
}

你可能感兴趣的:(【C++设计模式】)