注意事项
(1)根据原型模式的UML图可以知道,实现要依赖于抽象要不要依赖与具体
(2)拷贝构造函数是核心,而且针对c++要进行的是深拷贝
(3)克隆函数的关键就是调用拷贝构造函数
#include <iostream>
using namespace std;
class Student
{
protected:
int id;
char name[10];
public:
Student()
{
}
~Student()
{
cout<<"Desconstuct...."<<endl;
}
virtual Student *Clone()
{}
virtual void Show()
{ }
};
class StudentTypeA:public Student
{
public:
StudentTypeA(const char *name_input)
{
strcpy(name, name_input);
this->id = 0;
cout<<"Construction....."<<endl;
}
StudentTypeA(const StudentTypeA&other)
{
cout<<"Copy Construction..."<<endl;
this->id = other.id;
this->id ++;
strcpy(this->name, other.name);
}
virtual StudentTypeA *Clone()
{
StudentTypeA *tmp = new StudentTypeA(*this);
return tmp;
}
void Show()
{
cout<<"Student id == "<< id << " name == "<< name <<endl;
}
~StudentTypeA()
{
cout<<"Deconstruction StudentTypeA"<<endl;
}
};
int main()
{
Student *student1 = new StudentTypeA("fulima");
Student *student2 = student1->Clone();
Student *student3 = student2->Clone();
student1->Show();
student2->Show();
student3->Show();
return 0;
}