Question
What is the advantage of adding a static "builder()" method in the Builder Pattern?
I'm wondering about whether my implementation of the Builder pattern is wrong or not.
Let's say we have a User
class for which we want to have a Builder
, my implementation would be:
public class User
{
private final String name;
private final int age;
private User(Builder builder)
{
this.name = builder.name;
this.age = builder.age;
}
public static class Builder
{
//blah blah
public User build()
{
return new User(this);
}
}
}
But from time to time, I see that some people add this method:
public static Builder builder()
{
return new Builder();
}
for seemingly no reason other than achieving a slightly more readable syntax:
//Before
User user = new User.Builder()
.named("Tester")
.build();
//After
User user = User.builder()
.named("Tester")
.build();
Is this the only advantage? Do I miss anything?
2 61
2