Sobes.tech
Junior — Middle

Explain the principle of using the Builder pattern for object construction.

sobes.tech AI

Answer from AI

The Builder pattern is used for step-by-step creation of complex objects. It allows separating the construction process of an object from its representation, so the same process can create different representations.

Main idea:

  • Create a Builder class with methods to set various parameters of the object.
  • Each method returns the Builder itself, enabling method chaining (fluent interface).
  • At the end, the build() method is called, which returns the finished object.

This is convenient when an object has many parameters, and you want to avoid creating constructors with many arguments or multiple overloaded constructors.

Example in Java:

public class User {
    private final String firstName;
    private final String lastName;
    private final int age;
    private final String phone;
    private final 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)
    .setPhone("123456789")
    .setAddress("Pushkin St., 10")
    .build();
Explain the principle of using the Builder pattern… - sobes.tech