Builder Design Pattern
What is Builder Design Pattern?
- It is a creational design pattern.
- Actually, this pattern was introduced to solve some of the issues with Factory and Abstract Factory design patterns when the object contains a lot of attributes. i.e Focus of the pattern is on constructing a complex object step by step.
- The builder design pattern helps us to divide the operations/steps of building an object.
Real world analogy:
- Suppose you want to make a sandwich. It is complex process after all and we can leverage builder design pattern to create delicious sandwich step by step.
- This begins by deciding type of bread and number of slices of bread.
- Then we apply cheese, sauce or chutney depending upon choice/taste. Accordingly, we will prepare salad dressing.
- Then we get the ingredients of choice like tomato, capsicum, potato.
- After that, we will cut these vegetables properly.
- Now, we will begin to layer the vegetables.
- Finally, we will close sandwich followed by cutting it into pieces if required.
- Each step in the process can be thought of as a single step in the much larger builder pattern.
Example in software/application development:
- Suppose you’re creating Person class and it might be having multiple fields/attributes associated with it.
- These fields could be firstName, middleName, lastName, age, height, weight, address, phoneNumber, email, birthDate etc.
- Let’s consider, first four mentioned attributes are mandatory and the rest of attributes are optional.
- Here, having a constructor with multiple parameters will be verbose and error-prone from client code perspective. Also, providing multiple constructors or convenience constructors might be confusing for clients.
- Thus, builder pattern is an ideal choice for such scenario.
When to use builder design pattern?
- Whenever object instantiation requires configuring many attributes and some of them (or all of them) are optional.
- When you want to encapsulate complex creation logic in step by step manner.
- So, builder design pattern is better choice when we need to separate the construction of a complex object from its representation.
Comparison with factory method pattern:
- On the one hand, the factory is in charge of creating various subtypes of an object depending on the needs. Factory method pattern requires the entire object to be built in a single method call.
- On the other hand, in builder design pattern, different subtypes are also created by a builder pattern. Builder pattern requires to create the object in step by step methods.
Summary:
- Unlike other creational patterns that construct objects in one go, the Builder Pattern constructs the object step by step. It is used in creation of a complex object.