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.
- 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 very clean and readable way.
- Builder pattern is useful when there could be several flavors of an object. Or when there are a lot of steps involved in 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
Doorclass 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. At the end we have a method which uses constructor from
Door class and returns the
Then, we need to create constructor in model class
Observe that the
User constructor is private, so it can’t be accessed from the other class and we must use
Builder to create new object.
And that’s it. Go Try!