Junior — Middle
Can you name and explain the use of the Builder pattern in Java?
sobes.tech AI
Answer from AI
The Builder pattern in Java is used for step-by-step creation of complex objects, especially when a constructor with many parameters becomes inconvenient or unreadable. It allows creating an object by calling a chain of methods, each setting a specific property, and finally calling the build() method, which returns the finished object.
Advantages:
- Improves code readability
- Allows creating immutable objects
- Avoids constructors with long parameter lists
Example:
public class User {
private final String firstName;
private final String lastName;
private final int age;
private User(Builder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
}
public static class Builder {
private String firstName;
private String lastName;
private int age;
public Builder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public Builder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public Builder setAge(int age) {
this.age = age;
return this;
}
public User build() {
return new User(this);
}
}
}
// Usage:
User user = new User.Builder()
.setFirstName("Ivan")
.setLastName("Ivanov")
.setAge(30)
.build();
Thus, Builder simplifies creating objects with many parameters and makes the code more maintainable.