Builder Design Pattern
'Builder' is a creational design pattern that handles creating instances of complex objects. Once you exceed 4 or 5 parameters for your constructor, it becomes challenging to create instances of this object. In most cases, majority of these parameters are optional. Populating the constructor with nulls isn't an elegant approach, while overloading the constructor isn't ideal as you will end up having very many constructors in the end.
In such situations we prefer the builder pattern where we will instantiate these complex objects in a step by step manner specifying only what we need and then return an instance of the object based on those parameters. This will ensure that you code is clean and readable.
In Application
We have a burger stand set up where we prepare the burgers how our customers like it. We have the option of a regular burger(buns, a patty , some cheese and ketchup sauce ), but we prefer our customers to tell us what they want.
As you are aware, people have, it's fair to say, interesting preferences to how they want their burgers made.
Two customers, Suzzie and Kimotho come to our stand to make an order.
Here we have 2 different instances of the Burger object, each requiring different parameters. So how do we come up with a solution to this.
We could have different constructors for each but as we have seen, over time the number of constructors will grow and become unmanageable.
We could alternatively solve this problem partially by creating Burger and then adding 'ingredients' but that will impose another problem of leaving the object on inconsistent state during building, ideally the burger should not be available until it's created.
So here is how builder will solve this:
Here is the Burger object:
We then create a static nested class Builder in the Burger class.
We delegate the instantiation of the burger object to the builder class using the build() method.
Instantiation will be something like:
领英推荐
And output will be:
You can find the entire code sample here : Burger service
As with any other design pattern, builder has its advantages and disadvantages. here are a few:
Pros
Cons
In conclusion, it's important to note that design patterns are high-level templates to help developers in making design decisions. As such some scenarios will be ideal for Builder while others won't.
Checkout my previous article on factory design pattern here
And that's ...
How can we update our code to handle these new complexities?
Do we use a combination of Factory method pattern and builder?
Do we introduce another layer on top of the builder to handle how builders are instantiated?
I'll leave you with this food for thought .
Project Management | Strategy | Data Analyst
10 个月Very insightful! David Muchai I might not be a developer but this was easy to understand. Keep up!