Builder Design Pattern
Do you know how easy it is?
This design pattern is a part of the creational design pattern.
Let us discuss first why to use it?
Problem: You might have face the following issues while passing too many parameters in a method or constructor.
- There could be a change in the order of parameters passed in the constructor.
- You have to pass all the parameters, doesn't matter whether you want it or not.
Now let’s discuss how to solve these given problems. There are two solutions to solve the above problems.
- Using Setters methods.
- Using Builder design.
Let’s take an example and try to understand. So here we are having a Student class with 5 properties rollNo, name, class, age, mobileNo.
Here, we are creating student objects using the constructor and setters method.
Now, it’s time to see the Builder implementation.
Nothing big you need to do, just need to add a return this statement in all setters method and all done.
Hey, you noticed the difference, all this done in one line and we don’t need to worry about the order of parameters and we can set any number of parameters as many we want. Hence above mention, two problems are solved. Even it can be solved using the setters method also, but don’t you think we were writing too much line of code to create student.
Let me know in the comment section if you have any question or suggestions.
If you like this article and you learned something from this don’t forget to hit the clap button and share it with your friends also.