2
在構建器中聲明父類的實例並使用該變量初始化每個Field
並在構建器中再次分別聲明每個變量,然後聲明構建器作爲構造器的一部分來初始化每個Field
有什麼區別?這些構建器模式之間有什麼區別?
public class Foo {
public int i;
public String s;
private Foo(Builder builder) {
i = builder.i;
s = builder.s;
}
public static class Builder {
private int i;
private String s;
public Builder i(int i) {
this.i = i;
return this;
}
public Builder s(String s) {
this.s = s;
return this;
}
public Foo build() {
return new Foo(this);
}
}
}
public class Foo {
public int i;
public String s;
public static class Builder {
private final Foo mFoo = new Foo();
public Builder i(int i) {
mFoo.i = i;
return this;
}
public Builder s(String s) {
mFoo.s = s;
return this;
}
public Foo build() {
return mFoo;
}
}
}
刪除該樣板是我甚至考慮第二個的唯一原因。我的類包含了很多變量,並且有一個100多行代碼大部分來自setter的代碼,這有點讓人討厭。 – user4081847 2014-09-26 03:44:02