Welcome

首页 / 软件开发 / C++ / clone模式在平衡排序二叉树实现中的应用

clone模式在平衡排序二叉树实现中的应用2010-09-18wujinglongclone模式既prototype模式,是构造模式中的一种。其意图为:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

关键代码如下:

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方法。

clone模式有两个问题:

(一)内存泄漏,在clone函数中新建了一个对象,如果没有在外部接收它,它就不会自己释放自己。

(二)clone一个组件,如组合模式(composite)产生的抽象对象。

第一个问题的解决方案为智能指针,有很多文献介绍过这类问题。

这里讨论如何用clone模式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
}