Setter and (不是 OR 或 VS ) 生成器模式
2022-09-04 07:11:20
我有一种情况,我使用生成器模式来构造对象。最好的例子是披萨代码
public class Pizza {
private int size;
private boolean cheese;
private boolean pepperoni;
private boolean bacon;
public static class Builder {
//required
private final int size;
//optional
private boolean cheese = false;
private boolean pepperoni = false;
private boolean bacon = false;
public Builder(int size) {
this.size = size;
}
public Builder cheese(boolean value) {
cheese = value;
return this;
}
public Builder pepperoni(boolean value) {
pepperoni = value;
return this;
}
public Builder bacon(boolean value) {
bacon = value;
return this;
}
public Pizza build() {
return new Pizza(this);
}
}
private Pizza(Builder builder) {
size = builder.size;
cheese = builder.cheese;
pepperoni = builder.pepperoni;
bacon = builder.bacon;
}
}
目前为止,一切都好。
现在让我们假设一个用例,我需要.这需要一个.我从未见过构建器模式与 setter 共存的单一示例,这让我怀疑我所做的是一种反模式。update
cheese
setter
二传手和建造者可以共存吗?