Real-World Example
Imagine you are at Hardee’s and you order a specific deal, lets say, “Big Hardee” and they hand it over to you without any questions; this is the example of simple factory. But there are cases when the creation logic might involve more steps. For example you want a customized Subway deal, you have several options in how your burger is made e.g what bread do you want? what types of sauces would you like? What cheese would you want? etc. In such cases builder pattern comes to the rescue.In Plain Words
Allows you to create different flavors of an object while avoiding constructor pollution. Useful when there could be several flavors of an object. Or when there are a lot of steps involved in creation of an object.Wikipedia Says
The builder pattern is an object creation software design pattern with the intentions of finding a solution to the telescoping constructor anti-pattern.
The Telescoping Constructor Anti-Pattern
Having said that let me add a bit about what telescoping constructor anti-pattern is. At one point or the other we have all seen a constructor like below:Programmatic Example
The sane alternative is to use the builder pattern. First of all we have our burger that we want to make:When to Use?
When there are several flavors of an object
When there are several flavors of an object
When there could be several flavors of an object and to avoid the constructor telescoping. The key difference from the factory pattern is that; factory pattern is to be used when the creation is a one step process while builder pattern is to be used when the creation is a multi step process.
When you need step-by-step construction
When you need step-by-step construction
Use Builder when you need to construct a complex object step by step, where the construction process can vary based on the configuration.