Builder Design Pattern
We have multiple design patterns. Currently, we will discuss Builder.
Details
The Builder Pattern is a creational design pattern that allows the construction of complex objects step by step. It separates the construction of an object from its representation, enabling the same construction process to create different representations of an object.
To understand the Builder Pattern, let’s consider an example of a User class that represents a user profile. The user profile can have various optional attributes, such as a username, email address, age, and profile picture.
Get Amit Dhiman’s stories in your inbox
Join Medium for free to get updates from this writer.
Define the User class:
public class User {
private String username;
private String email;
private int age;
private String profilePicture;
// Private constructor to enforce the use of the builder
private User(UserBuilder builder) {
this.username = builder.username;
this.email = builder.email;
this.age = builder.age;
this.profilePicture = builder.profilePicture;
}
// Getters for user attributes
// ...
}Create a Builder class:
public class UserBuilder {
private String username;
private String email;
private int age;
private String profilePicture;
public UserBuilder(String username) {
this.username = username;
}
public UserBuilder setEmail(String email) {
this.email = email;
return this;
}
public UserBuilder setAge(int age) {
this.age = age;
return this;
}
public UserBuilder setProfilePicture(String profilePicture) {
this.profilePicture = profilePicture;
return this;
}
public User build() {
return new User(this);
}
}In this example, the User class represents the final object to be constructed, while the UserBuilder class provides the step-by-step building process.
Now, let’s see the usage of the builder:
User user = new UserBuilder("John")
.setEmail("john@example.com")
.setAge(30)
.setProfilePicture("profile.jpg")
.build();In this example, we create a User object using the UserBuilder by chaining the builder methods to set the desired attributes. The final build() method constructs the User object using the provided attributes.
The Builder Pattern allows us to create objects with optional or complex configurations while keeping the construction process readable and maintainable. It eliminates the need for multiple constructors with different parameter combinations and allows us to add or modify optional attributes without cluttering the constructor.
The Builder Pattern is particularly useful when dealing with objects that have a large number of optional or configurable attributes. It improves code readability, enhances flexibility, and promotes the creation of immutable objects.





