Builder design pattern in Java

The interesting thing about Builder is that you can find different variations of the builder.

For example, there is a variation of pattern with director class that is responsible for building objects.

And also there is a variation of builder pattern that called chain builder and allows to build new objects step by step.

Personally, I believe that the second variation is more popular.


Implementation with director.


To implement builder pattern with director we have to:

  • declare builder interface
  • create multiple builders
  • create director that can work with different builders
  • in client code instantiate director and concrete implementation of builder to build new objects


And this below is another version of builder pattern called chain builder.

To implement builder pattern with chain method calls we have to:

  • create inner Builder class inside type that we want to build
  • implement method in type that returns reference to the builder object
  • declare steers in builder that returns the reference to this builder object
  • implement build() method to terminate method chain and return target object
  • in client code call method to get reference to builder and build object step-by-step

The builder pattern simplifies the creation of objects. It also simplifies the code as your do not have to call a complex constructor or call several setter methods on the created object.

The builder pattern can be used to create an immutable class. 

References: https://blogs.oracle.com/javamagazine/post/exploring-joshua-blochs-builder-design-pattern-in-java

Comments

Popular posts from this blog

Debug Java Stream in Intellij Idea

Creating Efficient Docker Images with Spring Boot 2.3

CRUD Goes Even Easier With JPABuddy