DEV Community

Erwan Le Tutour
Erwan Le Tutour

Posted on

Builder design pattern — java

design-pattern

Definition of Builder Pattern

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.

Where to use the builder pattern?

When you have a simple object, this pattern is not very useful, but when you begin to have a more complex object and want to have a clear code you can use it without hesitation

For example :


A constructor with a limited number of parameters won’t be something that will make your code unreadable.
But what if now you have something like this :

The number of parameters to pass to the constructor will make the line of code unreadable.
Yes, you can still use the setter to change the value of a property after you have initialized your object. But what if all your fields are final because you want to render them immutable? (What they will be in the rest of this article) Or what if some fields are mandatory and others don’t?

Implementation of the builder pattern


I have used Lombok to not code the getter and the default constructor because the builder pattern doubles the number of lines of code.
So this is the implementation of my HumanBuilder, now how can I declare a Human with it? Nothing difficult you will see (or should I say read ?).

That will give this output
Human{
  name='Erwan', 
  lastName='null', 
  age=30, 
  height='null', 
  weight='null', 
  eyesColor='null', 
  hairColor='null', 
  birthPlace='Saint Cyr l'Ecole', 
  birthDate=null, 
  numberOfSibling=2, 
  married=true
}
Enter fullscreen mode Exit fullscreen mode

As you can see, I can choose the number of parameters to initialize and their order.

Discussion (0)