I am playing around with the Builder pattern and get stuck how to add a new "property" to a new-created object:
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;
}
}
I can create a new object with Builder like this:
MsProjectTaskData data = new MsProjectTaskData.Builder().withTransfered(true).build();
But with this approach the req
string from a new-created object is lost (of course).
Is there a possibility to create a new object with the new set isAlreadyTransfered
variable and with the "old" req
string from a "old" object?
Maybe I have to pass the old object reference to the Builder but I do not know how to do this. Maybe the use of Builder pattern is not really usefull for this approach?
EDIT: (After comment from Eugene)
Think, I got it:
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;
}
}
Seems to work or is something wrong with the code above? Can I use this approach without consideration?