C + + design pattern Shallow knowledge prototype mode

Source: Internet
Author: User
Definition: Specifies the kind of object created with the prototype instance, and creates a new object by copying the prototypes.

The prototype pattern is actually creating another customizable object from one object without needing to know the details of any creation.

Prototype mode mainly considers deep copy and shallow copy, in C + + class design, copy constructor is shallow copy, when overloaded assignment operator is deep copy.

Shallow copy: All variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object.

Deep copy: The Reference object's variable points to the copied new object, not the original referenced object.

Test Case:

[Code]int Main () {    //Generate Object    concreteprototype * Conproa = new Concreteprototype ();    Copy itself    concreteprototype *conprob = Conproa->clone ();   Clone after the first call copy constructor, Output:clone constructor    delete Conproa;    Conproa = NULL;    Delete Conprob;    Conprob = NULL;    return 0;}

Prototype mode (PROTOTYPE) implementation

[code]//interface class Prototype{public:    Prototype () {}    Virtual ~prototype () {}    Virtual Prototype *clone () = 0;};/ /Implementation Class Concreteprototype:public Prototype{public:    concreteprototype (): M_counter (0) {}    virtual ~ Concreteprototype () {}    //copy constructor    concreteprototype (const concreteprototype &RHS) {        Std::cout < < "constructor\n";        M_counter = Rhs.m_counter;    }    Copy itself    virtual Concreteprototype *clone () {        //Call copy constructor        std::cout << "clone\n";        return new Concreteprototype (*this);    } Private:    int m_counter;};

The above is the C + + design mode of shallow knowledge of the prototype model content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.