C ++ (with reference from the other party) Design Mode

Source: Internet
Author: User

In Java, there is a design pattern called holding the references of the other party.

 

However, in C ++, there are more powerful pointers. So that this design mode is not a design mode.

 

Let's take a look at how to use it.

 

 

First, let's look at a phenomenon.

 

Suppose there are Class A and Class B

 

If a contains a member variable of the B object type

B has a member variable of the type.

 

Then, the constructor B will be called when the object A is instantiated, And the constructor A will be called when the constructor B is called. This is an endless loop.

So what should I do if I really need this design?

 

At this time, the pointer becomes very powerful. (Of course, you can refer to the design mode referenced by the owner of Java)

You only need to have a pointer of the B type in a and a pointer of the type in B.

Of course, after doing so, it doesn't mean that everything is fine.

Constructor A and constructor B cannot call the constructor of the other party at the same time.

 

If neither of them calls the constructor of the other party, this is also possible, as long as there is a set method. So as to achieve the goal.

But the simple method is:

In a, new B. In B's constructor, set the parameter to (*).

A ()

{

New B (this)

}

 

 

 

 

 

 

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.