Junior — Middle
What functionality does the Builder pattern provide in the process of object development?
sobes.tech AI
Answer from AI
The Builder pattern is used for step-by-step creation of complex objects with many parameters, especially when a constructor with a large number of arguments is inconvenient or error-prone. It separates the process of constructing an object from its representation, allowing the creation of different variants of the object with the same construction process.
Main advantages:
- Improves code readability when creating objects with many parameters.
- Allows creating objects step-by-step, setting only the necessary parameters.
- Eliminates the need for multiple constructors with different parameters (telescoping constructor pattern).
Example in Java:
public class User {
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
public static class UserBuilder {
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
public UserBuilder setFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public UserBuilder setLastName(String lastName) {
this.lastName = lastName;
return this;
}
public UserBuilder setAge(int age) {
this.age = age;
return this;
}
public UserBuilder setPhone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder setAddress(String address) {
this.address = address;
return this;
}
public User build() {
return new User(this);
}
}
}
// Usage:
User user = new User.UserBuilder()
.setFirstName("Ivan")
.setLastName("Ivanov")
.setAge(30)
.build();