优信二手车:“优”无品质 “信”失归途
2025-11-07
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经验的会在Object中看到clone方法。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;
}
譬如一个链表结点类:
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
}
这样复制一个结点与复制一个链表统一起来了,不是很好吗?大功告成。...
for(all components of this object (this->o)){
if(this->o ==NULL){
pnew->o=NULL;
}else if(this->o 未被复制){
//复制本组件中的每一个元件
pnew->o = this->o->clone();
}else{
pnew->o = this->o 的复制品;
}
return pnew;
}
为判断组件 o 是否已经被复制应该在组件 o 中加一个标志cloned,cloned为真表示已经被复制。 为找到组件 o 的复制品应该在组件 o 中保存复制品的地址 pclone。
this->cloned=true;
this->pclone=pnew;
...
if(this->o == NULL)
pnew->o=NULL;
}else if(this->o->cloned==false){
//复制本组件中的每一个元件
pnew->o = this->o->clone();
}else{
pnew->o = this->o->pclone;
}
注意,执行一次clone操作后必须将cloned置false.class Node{
static int Cloned=0;
int cloned=0;
...
virtual Node * clone(){
...
if(cloned==Cloned){
//已经复制
...
}else{
//未复制
...
}
...
}
public:
Node * clone_for_call(){
Cloned++;
return clone();
}
...
}
评论 {{userinfo.comments}}
{{child.content}}



{{question.question}}
提交