C + + Implements Builder mode through internal classes

Source: Internet
Author: User

There is a good way to implement the builder pattern in Java. The builder mode is implemented here using C + + in the Java version.

In C + +, inner and outer classes are not directly related, and private objects of external classes cannot be accessed through an inner class, nor can private objects of inner classes be accessed through external classes. So the Friend keyword is used here to enhance the internal class's access to external classes, primarily by accessing the private constructors of the external classes. The code is as follows:

#include <iostream>#include<memory>using namespacestd;classbuilderdemo{ Public:    classBuilder { Public:        intservingsize; intservings; Builder (intServingsize,intservings): Servingsize (Servingsize), servings (servings) {} shared_ptr<BuilderDemo>build () {returnShared_ptr<builderdemo> (NewBuilderdemo (* This));    }    }; Private: Builderdemo (Constbuilder&builder) {Servingsize=builder.servingsize; Servings=builder.servings; } friendclassBuilder; Private:    intservingsize; intservings;};intMain () {Builderdemo::builder Builder (4, +); shared_ptr<BuilderDemo> demo =builder.build ();}

Some of the member variables of the external class are omitted here, and in general the builder mode can be used when the number of member variables for an external class is more than 4.

C + + Implements Builder mode through internal classes

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.