Class has several optional parameters for a solution:
1. The overlapping constructor pattern is feasible, but when there are many parameters, the client code is difficult to write and still more difficult to read.
2. JavaBeans mode, call a parameterless constructor to create the object, and then call the setter method to set each necessary parameter, as well as each dependent optional parameter.
Cons: The construction process is divided into several invocations, and JavaBean may be in an inconsistent state during construction. Prevents the possibility of making classes immutable, requiring programmers to ensure thread safety.
3. Builder mode, which simulates a named optional parameter.
Mode |
Excellent |
Inferior |
Overlapping constructors |
The simplest notation |
Difficult to read, difficult to write and difficult to use when multi-parameter |
JavaBeans |
Simple to create an instance |
The construction process may be inconsistent |
Builder |
Easy to write and easy to read when multi-parameter Consistent construction Process |
There is a cost to creating the builder |
//Example Builder mode Public classnutritionfacts {Private Final intServingsize;//Required Parameters Private Final intservings;//Required Parameters Private Final intFat//Optional Parameters Private Final intSodium//Optional Parameters Public Static classBuilder {Private Final intservingsize; Private Final intservings; Private intFat = 0; Private intSodium = 0; PublicBuilder (intServingsize,intservings) { This. servingsize =servingsize; This. servings =servings; } PublicBuilder Fat (intval) {Fat=Val; return This; } PublicBuilder Sodium (intval) {Sodium=Val; return This; } Publicnutritionfacts Build () {return NewNutritionfacts ( This); } } Privatenutritionfacts (Builder builder) {Servingsize=builder.servingsize; Servings=builder.servings; Fat=Builder.fat; Sodium=Builder.sodium; }}
// called New Nutritionfacts.builder (8). FAT (5). build ();
Traditional abstract factory implementations in Java are class objects that act as part of the build method with the Newinstance method. However, the Newinstance method always attempts to invoke the class's parameterless constructor, but some classes do not have a parameterless constructor and do not receive a compile-time error. The class.newinstance destroys the compile-time exception check.
"Reading notes-effective Java" 02. Consider using the builder when you encounter multiple constructor parameters