Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Builder pattern better than a Constructor with arguments in the Class's object being created?

Why can we not the different build steps within the constructor itself. if the build steps take arguments why can't they be provided as arguments to constructor and utilized within constructor to create the object.

AFAIK, in Builder pattern, the client which specific object to create; then what is the advantage in using a builder instead of a Constructor with arguments in the Class's object being created?

like image 407
user855 Avatar asked Sep 04 '10 07:09

user855


People also ask

What is the advantage of builder pattern?

Advantages of the Builder pattern include: Allows you to vary a product's internal representation. Encapsulates code for construction and representation. Provides control over steps of construction process.

What is the difference between builder and constructor?

The constructor constructs the object you need, while the builder is a helper object to construct what you need.

When should I use builder pattern in Java?

The builder pattern, as the name implies, is an alternative way to construct complex objects. This pattern should be used when we want to build different immutable objects using the same object building process.

What problem does the builder pattern solve?

Builder pattern solves the issue with large number of optional parameters and inconsistent state by providing a way to build the object step-by-step and provide a method that will actually return the final Object.


1 Answers

Oh! I get it. I was looking at the Wikipedia example and realized why Builder is helpful. It is helpful, when the client does not know which arguments to pass to the constructor as it is very complicated and hence cannot call the constructor directly and get the object. Consequently, he asks for help from the Concrete Builders who know what arguments to pass to constructors and hence get the object created.

Basically, if the client is the one who is mostly going to be passing the arguments to the constructor of the Class whose object is created, then Builder is not that helpful. It is perhaps better to use the prototype. On the other hand, if there is a small finite set of specific objects that can be created from the class by passing arguments to the constructor (or calling setters) to that class and if they are the ones that are frequently used, then it better to encapsulate this argument passing thingy in the Builder class and use them to create the objects for you.

like image 111
user855 Avatar answered Sep 26 '22 16:09

user855