Builder Design Pattern – When to Use It

design-patternsobject-oriented

I am currently learning about various object oriented design patterns. I came across a pattern called the builder pattern which is basically where you build a complex object through the use of creating simple objects that build on each other step by step.

My question is, in what scenarios would such a design pattern be appropriate? Which kind of tasks would benefit from such a design pattern?

Best Answer

Whenever creation of new object requires setting many parameters and some of them (or all of them) are optional.

E.g. (for Java but you can easily transform to other language)

User.builder()
       .name("John")
       .age(30)
       .sex(Sex.MALE)
       .build()

instead of

User user = new User();

user.setName("John");
user.setAge(30); 
...

You can also create easily objects for test with such a builder e.g.

User maleUserOver30() {
   return User.builder()
                 .sex(Sex.MALE)
                 .age(31)
                 .build();
}