简体   繁体   中英

Updating an object with builder pattern

I recently found about this pattern and tried to implement it into my project. It does what it suppose to do. However, tried to find a nice solution to update it. Came up with one solution and I would like to know if it is "acceptable".

Only one difference which I did is I created another constructor inside Builder class which takes calling object as parameter:

public Builder (User user) {
    this.userID = user.getUserID();
    this.userName = user.getUserName();
    ...
    //and so on

and in main method

creating an object:

User user = new User.Builder("mandatory params")
                    .email("some email")
                    .build();

and update:

user = new User.Builder(user).phoneNumber("my number").build();

Is this approach acceptable?

This is good if you want to create a new user with fields copied from another user, with some changes:

anotherUser = new User.Builder(user).phoneNumber("my number").build();

But if you are assigning the new object back to the user variable, it suggests that you are updating the existing user. To update, you are creating a whole new object and copying fields, which is very inefficient. You should use setters.

you should you setter's and getter's once you have the object empty or partially filled doesn't matter.

Also In my opinion it's better to use jackson objectMapper compare to builder pattern it automatically handles new parameters without adding extra line of code in the builder pattern and also it's more clean code .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM