When creating an object that requires passing in multiple parameters, we usually write different constructors based on the number of arguments, as follows
Public A (int a) {}
public A (int a, int b) {}
public A (int a, int b, int c) {}
Different constructors are called according to different parameters, but when there are many parameters, this method is not flexible enough , so we can implement the methods of dynamic parameter transfer.
Public A () {}
public void Seta (int a) {}
public void Setb (int b) {}
public void setc (int c) {}
This approach improves the readability of the parameters and increases the flexibility of the parameters, but increases the number of lines of code while causing strange errors when multithreaded asynchronously executes .
Is there any way to solve it? Improves code readability, increases parameter flexibility, does not increase the number of lines of code, and ensures thread safety?
Builder mode comes up with a look at the code first:
public class A {
private int A;
private int B;
private int C;
public static class Builder {
private int A;
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.A;
this.b = builder.b;
THIS.C = builder.c;
}
}
Call construction Method:
A = new A.builder (). Seta (1). SETB (2). SETC (3). build ();
This solves the problem mentioned above, but his shortcomings also exist, that is:
1. Constructors are complex to write
2. Cost of creating objects is relatively large
So the builder mode is only useful when you need to pass in many kinds of parameters, such as more than 4 kinds of parameters of the match, it is more cost-effective.
It is also worth noting that it is best to consider using the builder at the beginning of the design of the class, otherwise it would be inconvenient to extend the old constructor of the new builder together with maintenance.