A detailed description of builder model and its application in Android development

Source: Internet
Author: User

First, Introduction

In Android development, code that uses the builder pattern is ubiquitous, such as the use of the Android System dialog box Alertdialog or the use of the notification bar (Notification) in Android. For example, in some commonly used third-party libraries also can be seen in the trace, such as some common network request library such as okhttp or retrofit, or the picture loading library glide is not lack of its application.

Why is the builder mode so hot in Android or Java development? Because it is more flexible and encapsulating than a constructor or Get/set method, it has an advantage. The following is a concrete example of how to use the builder mode, the direct combination of code will be more intuitive.

Implementation of class instance initialization requirement

First of all, we need to ask:

Now we want to instantiate a class, as shown below, where some properties are required, and some are optional. As shown below:

public class User {    private final string mfirstname;//must select    Private final string mlastname;  Mandatory optional    private final String Mgender;  Optional    private final int mAge;  Optional    private final String Mphoneno;  Optional}

Method One:

* * Defines multiple overloads of the constructor implementation * Created by DB on 2017/6/23. */public class User3 {    private final String mfirstname;    Private final String Mlastname;    Private final String Mgender;    private final int mAge;    Private final String Mphoneno;    Public User3 (String mfirstname,string mlastname) {This        (Mfirstname,mlastname, "");    }    Public User3 (String mfirstname,string mlastname,string mgender) {This        (mfirstname,mlastname,mgender,0);    }    Public User3 (String mfirstname,string mlastname,string mgender,int mAge) {This        (Mfirstname,mlastname,mgender, MAge, "");    }    Public User3 (String mfirstname, String mlastname, String Mgender,int mage,string Mphoneno) {        this.mfirstname = Mfirs Tname;        This.mlastname = Mlastname;        This.mgender = Mgender;        This.mage = MAge;        This.mphoneno = Mphoneno;    }}

In method One, we used several overloaded constructors to initialize the requirements for different property values, and it is conceivable that if you want to implement all the possible attribute requirements, there will be a lot of overloaded versions of the constructors, making the code verbose and useless.

Method Two:

/** * uses Get/set * Created by DB on 2017/6/23. */public class User4 {private String mfirstname;    Private String Mlastname;    Private String Mgender;    private int mAge;    Private String Mphoneno;    Public String Getmfirstname () {return mfirstname;    } public void Setmfirstname (String mfirstname) {this.mfirstname = Mfirstname;    } public String Getmlastname () {return mlastname;    } public void Setmlastname (String mlastname) {this.mlastname = Mlastname;    } public String Getmgender () {return mgender;    } public void Setmgender (String mgender) {this.mgender = Mgender;    } public int Getmage () {return mAge;    } public void Setmage (int mAge) {this.mage = MAge;    } public String Getmphoneno () {return mphoneno;    } public void Setmphoneno (String mphoneno) {This.mphoneno = Mphoneno; }}

In Method 2, we used the get and set methods to set and read the property values, if so, we need to remove the final keyword of the property value, which means that the instance of the class is no longer immutable, with the original requirements, and the instance state of this class is not related, For example, if you want to create an instance of a class that has several property values at the same time, the instance will have a state of complete contact only if the last instance property's set function is called, which means the caller may see the discontinuous state of the class instance.

Method 3:

It's finally our builder model, and here we use the variant pattern in the builder mode, the code below:

/** * Created by DB on 2017/6/23.  */public class User {private final string mfirstname;//must select private final string mlastname;  Mandatory optional private final String Mgender;  Optional private final int mAge;  Optional private final String Mphoneno; The optional//constructor is private, the caller cannot instantiate the class directly, and it needs to be instantiated by the builder to instantiate private User (Userbuilder builder) {Mfirstname=builder.firstnam        E        Mlastname=builder.lastname;        Mgender=builder.gender;        Mage=builder.age;    Mphoneno=builder.phoneno;    }//provides only a Get method, not a set method, to ensure that the user class's immutable public String Getmfirstname () {return mfirstname;    } public String Getmlastname () {return mlastname;    } public String Getmgender () {return mgender;    } public int Getmage () {return mAge;    } public String Getmphoneno () {return mphoneno; }//constructor accepts only required attribute values as parameters, and only required property values are set to final to ensure that they set public static class Userbuilder {Private Final String in the constructor        FirstName; Private Final String LAStname;        Private String gender;        private int age;        Private String Phoneno;            Public Userbuilder (String firstname,string lastName) {this.firstname=firstname;        This.lastname=lastname;            } public Userbuilder Gender (String gender) {This.gender=gender;        return this;            Public Userbuilder Age (int.) {this.age=age;        return this;            } public Userbuilder Phoneno (String phoneno) {This.phoneno=phoneno;        return this;        Public user build () {Return to New user (this); }} public static void Main (string[] args) {User user = new Userbuilder ("ZHB", "PigNet"). Gend         ER ("male"). Age (+) Phoneno ("1234456"). Build ();         System.out.println (User.getmfirstname () + "" +user.getmlastname ());    System.out.println (User.getmage () + "" +user.getmgender ()); }}

Here we add a test case with the following results:

From the code above we can see the familiar chain programming, this way we will have the required property values as parameters to the builder constructor, and final, the other property values are implemented by the respective methods of the set, and finally in the build method to create a new class instance object, and return.

Iii. advantages and disadvantages of builder model

Advantages: The initialization of the class instance is divided into two parts, the initialization of the class instance is isolated from the target class (centralized into an inner class), avoids the excessive set method, and adopts the implementation of the call chain, which makes the code more concise and clear.

Cons: You need to write a lot of boilerplate code, we need to repeat the property definition of the external class user in the inner class Userbuilder

Iv. using plug-ins to generate code automatically

To circumvent the drawbacks in builder mode, we can simplify the builder mode creation process in Android Studio (Intelligent idea) by installing a plug-in called Innerbuilder.

Let's see how it works.

/** * Created by DB on 2017/6/23.    */public class User2 {private final String mfirstname;    Private final String Mlastname;    Private final String Mgender;    private final int mAge;    Private final String Mphoneno;        Private User2 (builder builder) {mfirstname = Builder.mfirstname;        Mlastname = Builder.mlastname;        Mgender = Builder.mgender;        MAge = Builder.mage;    Mphoneno = Builder.mphoneno;        public static final class Builder {private String mfirstname;        Private String Mlastname;        Private String Mgender;        private int mAge;        Private String Mphoneno;            Public Builder () {} public builder Mfirstname (String val) {mfirstname = val;        return this;            Public Builder Mlastname (String val) {mlastname = val;        return this;            Public Builder Mgender (String val) {mgender = val;        return this; } public Builder mAge (int val) {mAge = val;        return this;            Public Builder Mphoneno (String val) {Mphoneno = val;        return this;        Public User2 Build () {Return to New User2 (this); }    }}

In comparison with the previous example, it is not difficult to find that this section of automatically generated code is a little bit different from the code we wrote earlier, and we can modify it based on the actual requirements (as the previous required option takes the constructor to initialize the part)

A detailed description of builder model and its application in Android development

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.