Builder pattern is a Creational Design patter used in Object oriented programming, that provides a way to create complex objects step by step. It addresses multiple common problems encountered when creating objectwith many fields,especially some of the fields are optional or needed flexibility in construction process is needed.
This post explains why builder pattern is required and what problems it solves in software engineering.
In Object oriented programming, builder pattern used in the scenarios where an object has many properties, and it’s construction involves multiple steps or options.
Without this pattern, Object creation use a single or overloaded constructor to assign the properties. This pattern separates constructio process from the object final properties. This separation allows the same construction process to create different versions of an object depending on the number of steps.
For example, You are Making a sandwich. A Sandwitch can have bread as a required item, other items cheese and vegetables are optional.
Using this patter, We can build sandwitches with different combinations of bread, cheese and vegetables.
Components of a Builder pattern
- Sandwitch Class:
- Builder Class
When to Use the Builder Pattern
Following use cases are good to use the builder pattern
- if you need to create a complex object with many properties
- object creation logic contains complex logic
Advantages
- Readability improved: We don’t need to create a constructor for a complex object with many properties. It is easy to create a complex object with properties in step by step,