Java: Builder — design pattern
A Creational Design Pattern
Before you start, heads up to here for the simple introduction to the design patterns and the index to all the design patterns deep tutorials.
Defined
- The Builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.
- It simplifies object creation in a very clean and readable way.
Why, When?
- The builder pattern is useful when there could be several flavours of an object. Or when there are a lot of steps involved in the creation of an object.
- It’s very helpful when we have some model classes with many parameters. It saves us from polluting the object creation using the constructor. i.e,
new Pizza(veg: true, cheese: "mozzarella", spicy: false, thinCrust: false, wheatBase: true)
Code, Code, Code
We’ll continue with the example of Door which used in previous articles, we have some model class for the Door:
Now, instead of creating objects of this class using constructors, we will create them using Builder pattern like this:
Pretty simple, right?
To achieve this, we need to create a Builder
class inside Door
class which will have the methods to build our object. The key to having chaining methods is that builder methods return Builder
class. Look at the example below:
For every parameter we have a setter — the difference is that those methods return Builder
type. In the end, we have a method which uses the constructor from Door
class and returns the Door
object.
Then, we need to create the constructor in a model class Door
:
Observe that the Door
constructor is private, so it can’t be accessed from the other class and we must use Builder
to create a new object.
And that’s it. Go Try!