适用情况:
1:参数多
2:需要带参构造器多(避免冗余)
3:多线程并发情况
/**
* 线程安全的多参构建器实现
*
* @author 祥少
*
*/
public class Test {
private int a;
private int b;
private int c;
@Override
public String toString() {
return "Test [a=" + a + ", b=" + b + ", c=" + c + "]";
}
public Test(Build bd) {
a = bd.a;
b = bd.b;
c = bd.c;
}
public static class Build {
private int a;
private int b = 0;
private int c = 0;
public Build(int a) {
this.a = a;
}
public Build setB(int b) {
this.b = b;
return this;
}
public Build setC(int c) {
this.c = c;
return this;
}
public Test build() {
return new Test(this);
}
}
public static void main(String[] args) {
Test test = new Test.Build(100).setB(200).build();
System.out.println(test.toString());
}
}