The application of clone mode in the realization of the balanced-order binary tree

Source: Internet
Author: User

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
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.