Sobes.tech
Junior — Middle

Каково назначение и принцип работы паттерна Builder в программировании?

sobes.tech AI

Answer from AI

The Builder pattern is used for step-by-step creation of complex objects. Its main goal is to separate the construction of an object from its representation so that the same construction process can create different representations.

Working principle:

  • A separate Builder class is created, which contains methods for setting various parameters of the object.
  • Each method returns the Builder itself, allowing 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 a constructor with a large number of arguments becomes cumbersome.

Example in Java:

public class User {
    private String name;
    private int age;
    private String email;

    private User(Builder builder) {
        this.name = builder.name;
        this.age = builder.age;
        this.email = builder.email;
    }

    public static class Builder {
        private String name;
        private int age;
        private String email;

        public Builder setName(String name) {
            this.name = name;
            return this;
        }

        public Builder setAge(int age) {
            this.age = age;
            return this;
        }

        public Builder setEmail(String email) {
            this.email = email;
            return this;
        }

        public User build() {
            return new User(this);
        }
    }
}

// Usage:
User user = new User.Builder()
    .setName("Ivan")
    .setAge(30)
    .setEmail("ivan@example.com")
    .build();
Каково назначение и принцип работы паттерна Builder в… - sobes.tech