Java design mode--java Builder mode

Source: Internet
Author: User

1, the Java Builder mode is to instantiate an object with an inner class, avoid having too many constructors for a class, and it is easy to make mistakes if the constructor has default parameters.

Public person (String name)

Person (String name, int age)

Person (String name, int age, Boolean sex)

2. The request and response classes in the Android okhttp framework use Java Builder mode.

3. Here is a small example:

/** * @authorSunKing1927 November 2, 2015 * Java Builder Mode*/ Public classPerson {PrivateString name; Private intAge ; Private Booleansex;  PublicString GetName () {returnname; }     Public intGetage () {returnAge ; }     Public BooleanIssex () {returnsex; }     Public Static classBuilder {PrivateString name; Private intAge ; Private Booleansex;  PublicBuilder name (String N) {name=N; return  This; }         PublicBuilder Age (inta) { age=A; return  This; }         PublicBuilder Sex (Booleans) {sex=s; return  This; }         PublicPerson Build () {return NewPerson ( This); }    }    PrivatePerson (Builder builder) {name=Builder.name; Age=Builder.age; Sex=Builder.sex; }}
 Public class Mainrun {    publicstaticvoid  main (string[] argv) {        new Person.builder (). Name ("Stephenhe"). Age (+). Sex (true). Build ();         + "\ n" + person.getage () + "\ n" + Person.issex ());}    }

4. Reference Blog:

Http://www.cnblogs.com/moonz-wu/archive/2011/01/11/1932473.html

Java design mode--java Builder mode

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.