+ 1

Can anyone suggest a good, real world example of the builder design pattern?

Wondering if someone could suggest a good example of the builder design pattern, so one could get grasp of the concept.

23rd May 2017, 2:58 PM
Hina Hameed
Hina Hameed - avatar
2 odpowiedzi
+ 2
Suppose you want to create a Person object. That person has a number of different things about them we care about, their name, age, weight, height, gender, and maybe some other stuff as well. To create the object, our constructor would have to have a bunch of parameters and it would be difficult to read. Something like this: Person bob = new Person("Bob", 38, 180, 72, Gender.MALE); Instead, we like to use a Builder: Person bob = Person.builder() .setName("Bob") .setAge(38) .setWeight(180) .setHeight(72) .setGender(Gender.MALE) .build(); In the builder variant, we can easily see all of the things we have set and it's much clearer. Using a factory would also be just like the constructor. Also, a Builder could be used multiple times if only one or two values change between the build calls. Hope that helps!
6th Jun 2017, 6:01 AM
Jason Runkle
Jason Runkle - avatar
+ 1
I just built a version of this in C++ for your reference: https://code.sololearn.com/cvUIq31Ivg0k/?ref=app
6th Jun 2017, 3:54 PM
Jason Runkle
Jason Runkle - avatar