Builder模式處理多個構造器
阿新 • • 發佈:2019-01-06
Builder模式擁有重疊構造起器的安全性和JavaBeans模式的可讀性。的確,看起來程式碼舒服好多。當構造器引數比較多的時候推薦使用,構造器比較少的時候就不需要使用這個了。之前封裝OKhttp的時候,發現Request這個類就是使用這個模式,可以借鑑一下。
這個模式其實就是構建Builder靜態內部類,在Apple類的構造方法中初始化Apple物件。程式碼如下:
public class Apple {
private final int a;
private final int b;
private final int c;
private final int d;
private final int e;
public static class Builder {
private final int a;
private final int b;
private int c = 0;
private int d = 0;
private int e = 0;
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 Builder setE(int e) {
this.e = e;
return this;
}
public Apple build () {
return new Apple(this);
}
}
private Apple(Builder builder) {
this.a = builder.a;
this.b = builder.b;
this.c = builder.c;
this.d = builder.d;
this.e = builder.e;
}
public static void main(String[] args) {
Apple apple = new Apple.Builder(1, 1).setC(12).setD(14).build();//初始化物件
}
}
對比一下重疊構造器:
public class MyLinearLayout {
private int a;
private int b;
private int c;
private int d;
private int e;
public MyLinearLayout() {
this(0, 0);
}
public MyLinearLayout(int a, int b) {
this(a, b, 0);
}
public MyLinearLayout(int a, int b, int c) {
this(a, b, c, 0);
}
public MyLinearLayout(int a, int b, int c, int d) {
this(a, b, c, d, 0);
}
public MyLinearLayout(int a, int b, int c, int d, int e) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
}
}
有木有感覺可讀性高了好多。