Builder Pattern

 Builder Design Pattern

Another creational pattern that deals with the production of relatively complex objects is the Builder Design Pattern.

When the complexity of producing an item grows, the Builder pattern can divide the creation process by constructing the object with the help of another object (a builder).

Using a basic step-by-step technique, this builder may then be used to produce a variety of additional similar representations.



When to use Builder Design Pattern

  • When the process involved in creating an object is extremely complex, with lots of mandatory and optional parameters.
  • When an increase in the number of constructor parameters leads to a large list of constructors.
  • When client expects different representations for the object that's constructed.


Builder Design Pattern Implementation


Burger Class




BurgerBuilder Class



The BugerBuilder class has the same properties as the Burger class, which are required for passing values to the Burger constructor.

For every optional field to be set, the BurgerBuilder class exposes a setter-like method, which assigns the field’s value and returns the current BurgerBuilder instance to build the object in a fluent way. Since each method call returns the same BurgerBuilder instance, method calls can be chained, which makes the client code more concise and readable.




Employee Class






Output of the above code :





Advantages of Builder Design Pattern

  • The parameters to the constructor are reduced and are provided in highly readable method calls.
  • Builder design pattern also helps in minimizing the number of parameters in the constructor and thus there is no need to pass in null for optional parameters to the constructor.
  • Object is always instantiated in a complete state
  • Immutable objects can be built without much complex logic in the object building process.

Post a Comment

0 Comments