Java Creational Design Patterns – Builder Pattern

Builder pattern is one of the Creational design pattern. This pattern uses step by step approach to build a complex object. So we can say this pattern provides easy way to create a complex object.

NEED OF BUILDER PATTERN

In factory pattern, if client code sending many argument to factory class and if the type of parameters are same, then it’s difficult to maintain the order of the parameters so there may be a possibility of error.

For any class there are set of attributes out of which some are compulsory and some of optional. Factory pattern forces to send all parameters to class because of these restriction optional parameters need to send with value NULL.

So, by using Builder pattern, we can solve the problem with many numbers of optional parameters which is difficult to handle and will be problematic with Factory and Abstract Factory design patterns.

<Here are ALL Java Design Patterns, explained in detail with examples>

Builder Pattern by Example

Suppose, we have a Customer class with attributes firstName, lastName, age, phone, address and email. So, for this class, we need a constructor where you must pass all information as a parameters to constructor (if you want a immutable class). But in some cases, all attributes are not compulsory, few are optional. Hence, in such cases, we have to write down more constructors which increase the code size.

Builder pattern solves all these problems and provides a way to use many optional parameters with required parameters and preserves the immutability of Customer class.

Let’s see following java Example:

Here we have Customer class for which we are writing CustomerBuilder as a Builder class.

CustomerBuilder class will contain public constructor with mandatory parameters and this builder class will have methods to set optional parameters which returns the builder object after setting the value to the optional parameter.

And last is a build() method which is present in builder class which returns the complex object needed by client program. In customer class private constructor need to be written down by sending Builder class as an argument.

Code

Running the example

Output

Conclusion

This all about Builder pattern. As you can see in above program, that there is no need to pass NULL value for optional parameter and we are sending minimum (required parameter) to constructor, these optional parameters are easily handled in Builder design pattern.

<Here are ALL Java Design Patterns, explained in detail with examples>

Add a Comment

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