Effective Java-Consider the builder (Builder) when encountering multiple constructor parameters __java

Source: Internet
Author: User
Tags static class throw exception

This article is "effective Java" Reading notes, because it is a Java advanced book, it is inevitable that there will be an understanding of the deviation, if there is a mistake, very welcome to criticize, I am greatly appreciated.

What is a builder (Builder), a classmate who has been interviewed may have been asked to distinguish between string and StringBuffer and StringBuilder, and here is the StringBuilder string builder, Let's take a quick look at the use of this builder.

        String sb = new StringBuilder (). Append ("I")
                . Append ("AM").
                Append ("Student."). ToString ();

Let's take a look at the source code for the append () function here.

    @Override public
    StringBuilder append (String str) {
        super.append (str);
        return this;
    }

This append () adds the incoming str to the object string by invoking the method of the parent class, and returns the object, so that the append () method can be called continuously, and the object's uniqueness is persisted (string creates a new object each time).

Use the GetChars () method of string in the parent class method to add the character array value of the STR value we passed in.

    Public Abstractstringbuilder append (String str) {
        if (str = null) return
            appendnull ();
        int len = Str.length ();
        Ensurecapacityinternal (count + len);
        Adds str to the character array value to
        str.getchars (0, Len, value, count);
        Count = Len;
        return this;
    }

[note]. If you want to know how GetChars () works, you can view the JDK source code for string, which is no longer explained here.

And then we'll look at the last ToString () method

    @Override public
    String toString () {
        //Create a copy, don ' t share the array return
        new string (value, 0, CO UNT);
    }

This method generates a string that returns the past by using the value of the character array of value.

Above we may have a preliminary vague understanding of the builder, and then I'll give you a more accessible example to see the benefits of this builder.

Imagine a userinfo class that contains the following fields

Property Description whether it is necessary
Userid Primary key, User ID Is
UserName User name Is
Userposition User position (Java programmer must be male) Whether
Usersex Gender Whether
Userage Age Whether
UserEmail Mailbox Whether

In this class, the user ID, user name is necessary, the other is non-essential.

In the case of relatively much of this parameter, using the constructor to create the instance, the client code will appear to be more cumbersome, it will not be clear which parameter of the constructor corresponds to which value.

Of course, we can provide a setter method for each parameter, but there are two drawbacks to this approach.
(1) Because the construction process is divided into several invocations, it may be in an inconsistent state during the construction process. A class cannot guarantee consistency only by verifying the validity of constructor parameters.

[note] For this sentence, my personal understanding is as follows
For example, the above user class, we stipulate that if the position is a Java development engineer, the gender must be male.
However, because the setter method is divided into two parts to set the value, and the order of the set value is inconsistent, so the two parameters can not meet the above requirements.

(2) The Setter method cannot be used for some final classes.

So is there a way not only to meet the security of overlapping constructors, but also to meet the readability of the same as the use of setter.

This is when our builder (Builder) shines. Use builder into the following three steps: Use all the necessary fields (such as the user ID, user name) to generate a builder on builder the setter method to set some nonessential properties (you can set one or more, such as user sex and position association, at one time, If not satisfied, throw the exception). Calls to the Builder () method to generate immutable objects. (for example, the ToString () method in StringBuilder).

The instance code is as follows

Package com.blog.effective2;
 /** * @func Use Builder (Builder) * Created by Zhangjunqiang ~ on 2017/10/30.        * * Public class UserInfo {private final String userId;      Required private final String userName;
    Required private final String userposition;
    Private final String Usersex;
    Private final String Userage;

    Private final String UserEmail;        public static class Builder {private final String userId;      Required private final String userName;
        Required private String userposition = "";
        Private String Usersex = "";
        Private String userage = "";

        Private String UserEmail = "";
            Public Builder setuseremail (String email) {useremail = email;
        return this;
            Public Builder setusersexandposition (String sex, string position) {//[Java Programmer] with gender not [male], throw exception if (!) Male ". Equals (Sex)) &&" Java Programmer ". Equals (position)) {throW New runtimeexception ("parameter matching exception");
            } usersex = sex;
            Userposition = position;
        return this;
            Builder setuserage (String age) {userage = age;
        return this;
            Public Builder (String userId, String userName) {This.userid = UserId;
        This.username = UserName;
        }//Final build method public UserInfo build () {return new UserInfo (this);
        } public UserInfo (Builder Builder) {This.userid=builder.userid;
        This.username=builder.username;
        This.userposition=builder.userposition;
        This.userage = Builder.userage;
        This.useremail = Builder.useremail;
    This.usersex = Builder.usersex;
                @Override public String toString () {return "userinfo{" + "userid= '" + userId + ' \ "+ ", username= '" + userName + ' + ", userposition= ' "+ userposition + ' \" + ", usersex= '" + usersex + ' \ ' + ", userage= '" + Userag
    E + ' \ ' + ', useremail= ' + useremail + ' + ' + '} '; }
}

Like the next test code

    The public static void main (string[] args) {
        //format is consistent with StringBuilder.
        UserInfo userinfo=new Userinfo.builder ("001", "John"). Setuserage ("a").
                setuseremail ("test@test.com")
                . Setusersexandposition ("Male", "Java Programmer"). Build ();

        System.out.println (Userinfo.tostring ());

    }
    Output results
    //userinfo{userid= ' 001 ', username= ' John ', userposition= ' Java Programmer ', usersex= ' men ', userage= ', useremail= ' Test@test.com '}

In this mode, additional expenses are created by creating an object at the same time as creating the corresponding builder object.

In short, if you have multiple parameters for a class, consider using the builder pattern (the builder mode behaves better when there are many parameters in the class that are unnecessary).

2017/10/30 13:05 at Fuzhou University.

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.