Posted on Leave a comment

Builder Pattern In Java

Keys to remember

  • Outer class has a public static Builder class
  • Outer class has a private constructor that takes an instance of the builder
  • The Builder has method to set value to the properties
  • The Builder class has a build() method that call the outer class’ constructor (that takes one Builder instance)
  • Inside the outer’s private constructor, the outer’s properties are set to that of the Builder instance

Sample code

public class Breakfast {

    private String food, drink;

    public static class Builder
    {
        private String food, drink;

        public Builder food(String food)
        {
            this.food = food;
            return this;
        }

        public Builder drink(String drink)
        {
            this.drink = drink;
            return this;
        }

        public Breakfast build()
        {
            return new Breakfast(this);
        }
    }

    private Breakfast(Builder builder)
    {
        this.food = builder.food;
        this.drink = builder.drink;
    }

    public void stateOrder()
    {
        System.out.println(new StringBuilder("I need ").append(this.food).append(" and ").append(this.drink).toString());
    }



    public String getFood() {
        return food;
    }

    public String getDrink() {
        return drink;
    }


    public static void main(String[] args) {
        Breakfast b = new Builder().drink("Coffee").food("Beef").build();

        b.stateOrder();
    }
}

Questions

  • Is the Builder pattern only good for setting properties?
Leave a Reply

Your email address will not be published. Required fields are marked *