Java builder Mode
When you need to input multiple parameters to create an object, we usually write different constructors according to the number of parameters, as shown below:
Public A (int ){}
Public A (int a, int B ){}
Public A (int a, int B, int c ){}
Different constructors are called based on different parameters, but when there are too many parameters,This method is not flexible enoughSo the method for dynamically passing parameters is implemented.
Public (){}
Public void seta (int ){}
Public void setb (int B ){}
Public void setc (int c ){}
This method improves the readability of parameter passing and the flexibility of parameter passing. HoweverIt will increase the number of lines of code and cause strange errors during asynchronous multi-thread execution..
Is there a solution? It not only improves code readability, parameter flexibility, but also does not increase the number of lines of code and ensures thread security?
Builder mode debut, first look at the Code:
Public class {
Private int;
Private int B;
Private int c;
Public static class Builder {
Private int;
Private int B;
Private int c;
Public Builder (){}
Public Builder seta (int a) {this. a = a; return this}
Public Builder setb (int B) {this. B = B; return this}
Public Builder setc (int c) {this. c = c; return this}
Public A build () {return new A (this )}
}
Private A (Builder builder ){
This. a = builder.;
This. B = builder. B;
This. c = builder. c;
}
}
Call constructor:
A a = new A. Builder (). seta (1). setb (2). setc (3). build ();
In this way, the problems mentioned above are solved, but their shortcomings also exist:
1. the constructor is very complicated to write
2. Large Object creation overhead
Therefore, the builder mode is more cost-effective only when many parameters need to be input, such as the combination of more than four parameters.
It is worth noting that:It is best to consider whether to use the builder at the beginning of the class design, otherwise it will be inconvenient to extend the new builder and the old constructor together for maintenance in the future.