what is Builder
Builder is a creational design pattern. It helps you construct complex objects step by step and the final step will return the object. The process of constructing an object should be generic so that it can be used to create different representations of the same object.
Example
Suppose we want to make a Lunch Order. It has a bunch of items such as bread, condiments, dressing, and meat, in reality, even more complex objects. if we use tradition way, that would require a bunch of and complex constructors to achieve that. Check out below example to understand the Builder Patter.
1 | public class LunchOrder { |
Below shows how to use builder to build our object:
1 | public class TestApp { |
Advantages
Use the builder pattern to get rid of a “telescopic constructor”.
say you have a bunch of parameters, to fulfill various requirements, you have to create different constructors.
java1
2
3
4
5
6class Bread{
Bread(){...}
Bread(String p1,String p2){...}
Bread(String p1,String p2,String p3){...}
//...
}The builder pattern lets you build objects step by step, with only those steps/ parameters that you really need.
Builder Pattern can help to create different representtations of some product.
This requires you to build base builder interface defines all possible construction steps. And concrete builders implement these steps to consturst particular representations of the product.
Use the Builder to construct Composite trees or other comple objects.
The Builder pattern lets you construct products step-by-step. You could defer execution of some steps without breaking the final product. You can even call steps recursively, which comes in handy when you need to build an object tree.
A builder doesn’t expose the unfinished product while running construction steps. This prevents the client code from fetching an incomplete result.








