Design Pattern (Part 04) — Builder Design Pattern

The builder pattern is a creational pattern that refers to that “construct a complex object from simple objects using a step-by-step approach”. The Builder Pattern uses the step-by-step approach in building complex objects using basic simple objects. The pattern allows you to produce different types and representations of an object using the same construction code.

The name Builder refers to build objects. Sometimes, the objects we create can be complex, made up of several sub-objects, or require an elaborate construction process.

builder pattern encapsulates or hides the process of building a complex object and separates the representation of the object and its construction. The separation allows us to construct different representations using the same construction process.

Creating a subclass for every possible configuration of an object

● When building a composite structural object
● When the construction process must allow different representations for the object that’s constructed

  1. Given better control over the construction process.
  2. Given a clear separation between the construction and representation of an object.

Implement a builder design pattern

  1. First, need to create a static nested class and then copy all the arguments from the outer class to the Builder class. We should follow the naming convention and if the class name is Computer then the builder class should be named as ComputerBuilder.
  2. Java Builder class should have a public constructor with all the required attributes as parameters.
  3. Java Builder class should have methods to set the optional parameters and it should return the same Builder object after setting the optional attribute.
  4. The final step is to provide a build() method in the builder class that will return the Object needed by the client program. For this, we need to have a private constructor in the Class with Builder class as an argument.

Usecase of Builder Design Pattern

For this scenario, we have used a query building use case in databases. We have a class called Phone, which contains private attributes as OS, ram, processor, screenSize and battery. The PhoneBuilder class has a property to hold a Phone object, and it will create a Phone object inside of its constructor. PhoneBuilder will have methods to set OS, ram, processor, screenSize and battery to the Phone object, and each method will return a PhoneBuilder object for the chaining process. Finally, it will implement a method called getPhone() to returns the Phone object at which we are looking for. If we pass values only for OS, ram, and battery, for other variables shows the results as a default value.

You can find the implementation code for this scenario please go through the below Github link:

References:

Software Engineer at Virtusa (Pvt) Ltd.