Builder Design Pattern
Builder Design Pattern
2. Builder: The Builder is responsible for creating the parts that make up
the product, and for assembling those parts into the final product.
The Builder pattern is useful when the process for creating a complex
object is time-consuming or complex, and the object can be created in
multiple ways with different configurations. By separating the
construction process from the representation of the object, the Builder
pattern allows the user to create objects in a more flexible and
customizable way.
```
public class User {
private String firstName;
private String lastName;
private int age;
private String address;
private String email;
In this example, we have a User class with private fields for firstName,
lastName, age, address, and email. We also have a private constructor
that takes a UserBuilder object as a parameter, and sets the fields of
the User object to the values specified in the UserBuilder.
The UserBuilder is a static inner class that has fields for firstName,
lastName, age, address, and email, along with setter methods for each
field. It also has a build method that returns a new User object
constructed using the fields in the UserBuilder.
```
User user = new User.UserBuilder("John", "Doe")
.setAge(30)
.setAddress("123 Main St.")
.setEmail("[email protected]")
.build();
```
This creates a new User object with the firstName "John", lastName
"Doe", age 30, address "123 Main St.", and email
"[email protected]". The UserBuilder allows for the creation of a
customizable User object without having to specify all the parameters
in the constructor.