Java best way to implement builder pattern

Small Note : Yes the properties might be a repeat but they have advantages

Details below : If you look at the details here.

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

Notice below method in Builder and respective constructor or parent Pizza class - full code in link here

 public static class Builder {

    public Pizza build() {    // Notice this method
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {  // Notice this Constructor
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }

I think in your case there is no matter where to create the object. The builder would be used the same way in both cases with minimum difference in performance.

But if the object is immutable and it's field could be created with more than one step then I would certainly go with the second approach. For example you can check the source code of java.lang.StringBuilder and see that the String object is created in the last step:

public String toString() {
    // Create a copy, don't share the array
    return new String(value, 0, count);
}

Moreover I prefer the Wizard pattern. It is an extension of the Builder pattern which protects you from getting IllegalStateException.

public class Person {

    private String firstName;
    // other properties ...

    private Person() {}

    // getters ...

    public static class Builder {

        public Builder() {}

        public FirstStep setFirstName(String firstName) {
            return new FirstStep(firstName);
        }

        public static class FirstStep {

            private String firstName;

            private FirstStep(String firstName) {
                this.firstName = firstName;
            }

            public Person build() {
                Person person = new Person();
                person.firstName = firstName;
                return person;
            }
        }
    }
}

The Builder pattern has been described in the Gang of Four “Design Patterns” book that says:

The builder pattern is a design pattern that allows for the step-by-step creation of complex objects using the correct sequence of actions. The construction is controlled by a director object that only needs to know the type of object it is to create.

If there is a sequence of steps that needs to be followed while constructing the object then go for second option.

In your first option correct sequence of actions are not controlled. You can go for either option if sequence of actions are not defined.

Tags:

Java

Builder