For this week’s blog post I will be taking a look at the Builder Design Pattern and how it is effectively implemented and used within a Java program. The Builder Design Pattern is designed to provide a flexible solution to various object creation problems that may arise within object-oriented programming. The pattern is used to separate the construction of a complex object from its representation. The Builder pattern is a creational pattern.
For this pattern we will use a common class, the Employee class. Suppose you have an Employee class with multiple instance variables some of which are required and others that are not. What type of constructor is required for this type of class? One could follow the telescoping constructor pattern, which would require multiple constructors all with different forms of required attributes as parameters, but this is tedious and inefficient. Having multiple constructors with varying parameters can lead to confusion of which constructor to invoke when, the default values of the parameters, and what could happen if you pass the wrong value to a constructor.
This leads us to the Builder Pattern. In order to implement the Builder pattern for this example, you would need to create a public static nested class which contains all the instance attributes from the outer class. The outer Employee class will have a private constructor that takes the EmployeeBuilder object as an argument. The builder class will have a public constructor that has all the required attributes as parameters defined as “final”. The builder class will also have setter methods to set the optional parameters. The final step is to provide a build() method in the builder class tat will return the other class object to the client. The method will call the private constructor in the other class, passing the Builder object as the parameter to this private constructor. The Employee class will only have getter methods and no public constructor. This means that the only way to get an Employee object is through the nested EmployeeBuilder Class.
The Builder pattern is useful in situations where a class has multiple attributes that may be the same type or optional. Instead of creating multiple constructors, we can build a separate class that will build the object and provide setter methods to set the optional attributes.