Item 2 encountered multiple constructor parameters consider builder Builder
1. What is Builder?
1 Public classBuilder_pattern {2 Private Final intP1;3 Private Final intP2;4 Private Final intP3;5 Private Final intP4;6 7 Public Static classbuilder{8 Private Final intP1;9 Private Final intP2;Ten One Private intP3=0; A Private intP4=0; - - PublicBuilder (intP1,intp2) { the This. p1=P1; - This. p2=P2; - } - PublicBuilder P3 (intval) { +P3=val;return This; - } + PublicBuilder P4 (intval) { AP4=val;return This; at } - PublicBuilder_pattern Build () { - return NewBuilder_pattern ( This); - } - } - in PrivateBuilder_pattern (Builder builder) { -p1=builder.p1;p2=builder.p2;p3=builder.p3;p4=BUILDER.P4; to } + - the //builder_pattern bp=new builder_pattern.builder. P3 (1). P4 (1). build (); Note the P3 P4 return type is Builder can be called continuously! *}
2. The benefits of using the builder.
Elegant in the multi-parameter, the parameters are readable, ensure thread safety, suitable for class inheritance.
3, the disadvantage of using the builder.
The cost is higher, so it is recommended when there are many parameters, especially when there are many optional parameters.
Effective Java 1