I play with the Builder pattern and loop how to add a new “property” to the new object being created:
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 as follows:
MsProjectTaskData data = new MsProjectTaskData.Builder().withTransfered(true).build();
But with this approach, the req line from the created new object is lost (of course).
Is it possible to create a new object with the new variable isAlreadyTransfered and with the string "old" req from the "old" object?
Maybe I need to pass the old link to the Builder object, but I don't know how to do this. Maybe using the Builder pattern is not very useful for this approach?
EDIT: (After a comment from Eugene)
Think I understood:
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; } }
It seems to work or something is wrong with the code above? Can I use this approach without consideration?
source share