遇到多个构造器参数时, 要考虑采用构建器(Builder)
Java代码
public A
private int a;
private int b;
private int c;
private int d;
public static class Builder{
// 必须的
private final int a;
private final int b;
private int c;
private int d;
public Builder(int a, int b){
this.a=a;
this.b=b;
}
public Builder setC(int c){
this.c = c;
return this;
}
public Builder setD(int d){
this.d=d;
return this;
}
public A build(){
return new A(this);
}
private A(Builder builder){
a = builder.a;
b = builder.b;
c = builder.c;
d = builder.d;
}
}
使用:
A a = new A.Builder(1, 2).setC(3).setD(4).build();
如果类的构造器或者静态工厂中具有多个参数, 设计这种类时, Builder模式就是一种不错的选择. 特别是大多数参数都是可选的时候. 与使用传统的重载构造器模式相比, 使用Builder模式的客户端将更易于阅读和编写.
Java代码
public A
private int a;
private int b;
private int c;
private int d;
public static class Builder{
// 必须的
private final int a;
private final int b;
private int c;
private int d;
public Builder(int a, int b){
this.a=a;
this.b=b;
}
public Builder setC(int c){
this.c = c;
return this;
}
public Builder setD(int d){
this.d=d;
return this;
}
public A build(){
return new A(this);
}
private A(Builder builder){
a = builder.a;
b = builder.b;
c = builder.c;
d = builder.d;
}
}
使用:
A a = new A.Builder(1, 2).setC(3).setD(4).build();
如果类的构造器或者静态工厂中具有多个参数, 设计这种类时, Builder模式就是一种不错的选择. 特别是大多数参数都是可选的时候. 与使用传统的重载构造器模式相比, 使用Builder模式的客户端将更易于阅读和编写.