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 classUser {Private FinalString Mfirstname;//must-Choose Private FinalString Mlastname;//must-Choose Private FinalString Mgender;//options available Private Final intMAge;//options available Private FinalString Mphoneno;//options available}
Method One:
** *constructor implementation that defines multiple overloads* Created by DB on 2017/6/23. */ Public classUser3 {Private FinalString Mfirstname; Private FinalString Mlastname; Private FinalString Mgender; Private Final intMAge; Private FinalString Mphoneno; PublicUser3 (String mfirstname,string mlastname) { This(Mfirstname,mlastname, ""); } PublicUser3 (String mfirstname,string mlastname,string mgender) { This(mfirstname,mlastname,mgender,0); } PublicUser3 (String mfirstname,string mlastname,string Mgender,intMAge) { This(Mfirstname,mlastname,mgender,mage, ""); } PublicUser3 (String mfirstname, String mlastname, String Mgender,intmage,string Mphoneno) { This. Mfirstname =Mfirstname; 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:
/*** Get/set * Created by DB on 2017/6/23.*/ Public classUser4 {PrivateString Mfirstname; PrivateString Mlastname; PrivateString Mgender; Private intMAge; PrivateString Mphoneno; PublicString Getmfirstname () {returnMfirstname; } Public voidsetmfirstname (String mfirstname) { This. Mfirstname =Mfirstname; } PublicString Getmlastname () {returnMlastname; } Public voidsetmlastname (String mlastname) { This. Mlastname =Mlastname; } PublicString Getmgender () {returnMgender; } Public voidSetmgender (String mgender) { This. Mgender =Mgender; } Public intGetmage () {returnMAge; } Public voidSetmage (intMAge) { This. MAge =MAge; } PublicString Getmphoneno () {returnMphoneno; } Public voidSetmphoneno (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 classUser {Private FinalString Mfirstname;//must-Choose Private FinalString Mlastname;//must-Choose Private FinalString Mgender;//options available Private Final intMAge;//options available Private FinalString Mphoneno;//options available//The constructor is private, the caller cannot instantiate the class directly, and it needs to be instantiated by builder PrivateUser (Userbuilder builder) {Mfirstname=Builder.firstname; Mlastname=Builder.lastname; Mgender=Builder.gender; MAge=Builder.age; Mphoneno=Builder.phoneno; } //provides a Get method only, without a set method, to ensure the immutability of the user class PublicString Getmfirstname () {returnMfirstname; } PublicString Getmlastname () {returnMlastname; } PublicString Getmgender () {returnMgender; } Public intGetmage () {returnMAge; } PublicString Getmphoneno () {returnMphoneno; } //The constructor accepts only the required property values as parameters, and only the required property values are set to final to ensure that they are set in the constructor Public Static classUserbuilder {Private FinalString FirstName; Private FinalString LastName; PrivateString Gender; Private intAge ; PrivateString Phoneno; PublicUserbuilder (String firstname,string lastName) { This. firstname=FirstName; This. lastname=LastName; } PublicUserbuilder Gender (String gender) { This. gender=gender; return This; } PublicUserbuilder Age (intAge ) { This. age=Age ; return This; } Publicuserbuilder Phoneno (String phoneno) { This. phoneno=Phoneno; return This; } PublicUser Build () {return NewUser ( This); } } Public Static voidMain (string[] args) {User User=NewUserbuilder ("ZHB", "PigNet"). Gender ("Male"). Age (25). 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 classUser2 {Private FinalString Mfirstname; Private FinalString Mlastname; Private FinalString Mgender; Private Final intMAge; Private FinalString Mphoneno; PrivateUser2 (Builder builder) {Mfirstname=Builder.mfirstname; Mlastname=Builder.mlastname; Mgender=Builder.mgender; MAge=Builder.mage; Mphoneno=Builder.mphoneno; } Public Static Final classBuilder {PrivateString Mfirstname; PrivateString Mlastname; PrivateString Mgender; Private intMAge; PrivateString Mphoneno; PublicBuilder () {} PublicBuilder Mfirstname (String val) {mfirstname=Val; return This; } PublicBuilder Mlastname (String val) {mlastname=Val; return This; } PublicBuilder Mgender (String val) {Mgender=Val; return This; } PublicBuilder MAge (intval) {MAge=Val; return This; } PublicBuilder Mphoneno (String val) {Mphoneno=Val; return This; } PublicUser2 Build () {return NewUser2 ( 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