1. Overview
In this tutorial, we'll look at the Builder Pattern and how we can implement it in Java.
2. When to Use
Let's say that we have a class with multiple properties. Moreover, it has various construction rules leading to multiple internal representations.
To handle each representation, we can create multiple constructors. However, this can be cumbersome and hard to manage. It also leads to duplicate code.
Telescoping constructors can help us in reducing the code duplication. But nevertheless, creating a different class to handle this construction process is a better approach.
3. How to Implement
The Builder Pattern has different flavors. We'll investigate the builder implementation that is created as an inner static class:
Here we have the Person and Builder classes. Since the builder class constructs the target object, it must define the same properties. As we can see Builder has all the properties Person defines.
Immutability is another important point when working with builders. The target class must be immutable. Hence Person has a private constructor and doesn't have any setter methods.
Additionally, the builder class maintains the variants by validating the input. As a result, we can't have a Person object with an inconsistent state.
Lastly, let's look at the client code:
4. Summary
In this tutorial, we've looked at the usage of the Builder Pattern.
As always, the source code for all examples is available on Github