主要是为了进行复制自身
拷贝分为浅拷贝和深拷贝,后者将会连带指针指向的内容一并拷贝。
C++中通过拷贝构造函数实现。
UML类图
C++代码:
class Prototype
{
public:
virtual Prototype* clone() const= 0;
virtual ~Prototype(){}
};
class ConcretePrototype : public Prototype
{
public:
ConcretePrototype(){}
ConcretePrototype(const ConcretePrototype& cp)
{
cout<<"一些具体的复制过程"<<endl;
}
virtual Prototype* clone() const
{
return new ConcretePrototype(*this);
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Prototype* p = new ConcretePrototype;
Prototype* p1 = p->clone();
system("pause");
return 0;
}
代码很简单,就是简单的自身复制。下章将复习结构型的模式了。