Builder mode:
Mainly solve the problem of too many constructor parameters;
Cause : The object has multiple global variables;
Workaround :
1. Multiple construction methods, the first one passed in is mandatory, and the subsequent construction methods add optional parameters in turn; similar to the construction method of custom view ;
Disadvantages: poor readability; troublesome to call, such as two required parameters, and when you want to pass the fourth parameter, you must first set the default value for the third parameter;
2. Empty constructor, set setter and getter for each property ;
Disadvantages : The object will produce an inconsistent state, and all set methods must be called after the completion; the class is mutable, and the benefits of immutable classes are lost.
Builder:
Steps :
1. The properties of the class are immutable, modified with final , the value is set in the constructor, and only the getter method is provided to the outside world ;
2. Private constructor, the parameter is the internal static class Bulider ;
3. For the internal static class Builder , the parameters in the construction method only receive the required ones ; for optional parameters, they are set by the methods whose return value is the Builder object;
4. Finally , build a build method whose return value is an external User object in the Builder class to new out the object;
Advantages : Solve the shortcomings of the first two methods; chained calls are more readable; Builder 's inner class construction method only accepts required parameters and is modified with final ;
Disadvantages : generate redundant Builder objects and consume memory; Builder is usually decorated with static , and all property methods of static classes are not in memory before they are loaded into the JVM ;
Note : Since Builder is not thread-safe, to check the validity of a variable in the Builder inner class, you must wait until the object is created before checking;
Example : AlertDialog;
Reference : http://www.jianshu.com/p/e2a2fe3555b9