我正在玩 Builder 模式并被困在如何将新的“属性”添加到新创建的对象中:
public class MsProjectTaskData {
private boolean isAlreadyTransfered;
private String req;
public static class Builder {
private boolean isAlreadyTransfered = false;
public Builder withTransfered(boolean val) {
isAlreadyTransfered = val;
return this;
}
public MsProjectTaskData build() {
return new MsProjectTaskData(this);
}
}
private MsProjectTaskData(Builder builder) {
isAlreadyTransfered = builder.isAlreadyTransfered;
}
public MsProjectTaskData(String req) {
this.req = req;
}
}
我可以像这样使用 Builder 创建一个新对象:
MsProjectTaskData data = new MsProjectTaskData.Builder().withTransfered(true).build();
但是使用这种方法,req
来自新创建对象的字符串会丢失(当然)。
是否有可能使用新的集合isAlreadyTransfered
变量和来自“旧”对象的“旧”req
字符串创建一个新对象?
也许我必须将旧对象引用传递给 Builder,但我不知道该怎么做。也许使用 Builder 模式对于这种方法并没有真正的用处?
编辑:(来自尤金的评论后)
想想,我明白了:
public static class Builder {
private boolean isAlreadyTransfered = false;
private MsProjectTaskData data;
public Builder(MsProjectTaskData data) {
this.data = data;
}
public Builder withTransfered(boolean val) {
isAlreadyTransfered = val;
data.setAlreadyTransfered(isAlreadyTransfered);
return this;
}
public MsProjectTaskData build() {
return data;
}
}
似乎工作或上面的代码有问题?我可以不加考虑地使用这种方法吗?