Clone mode is both prototype mode and one of the construction patterns. The intention is to use a prototype instance to specify the type of object to create, and to create a new object by copying the prototypes.
The key code is as follows:
virtual product * prototype::clone(){
return new prototype(this->datas);
}
virtual product * concreteprototype_1::clone(){
//return copy of self
return new concreteprototype_1(this->datas);
}
virtual product * concreteprototype_2::clone(){
//return copy of self
return new concreteprototype_2(this->datas);
}
Java-experienced will see the Clone method in object.
There are two issues with clone mode:
(a) memory leak, a new object is created in the Clone function, and it does not release itself if it is not received externally.
(ii) Clone an abstract object produced by a component, such as a combination mode (composite).
The solution to the first problem is the smart pointer, and there are a lot of references to this type of problem.
This discusses how to clone a component in clone mode.
virtual component * component::clone(){
component * pnew = new component(this->datas);
for(all components of this object (this->o)){
if(this->o != NULL)
//复制本组件中的每一个元件
pnew->o = this->o->clone();
}
return pnew;
}
For example, a linked list node class:
class Node{
private:
DataType datas;
Node * next;
public:
virtual Node* clone(){
Node* pnew=new Node(this->datas);
if(this->next != NULL)pnew->next = this->next->clone();
return pnew;
}
//other codes
}