Junior — Middle
Какое назначение у паттерна Builder в разработке программного обеспечения?
sobes.tech AI
Answer from AI
The Builder pattern is used for step-by-step creation of a complex object. Its main purpose is to separate the construction process of an object from its representation so that the same construction process can create different representations.
This is useful when an object has many parameters or a complex structure, and creating it directly through a constructor is inconvenient or confusing.
Example in Java:
class Car {
private String engine;
private int wheels;
private String color;
// setters and getters
}
class CarBuilder {
private Car car = new Car();
public CarBuilder setEngine(String engine) {
car.setEngine(engine);
return this;
}
public CarBuilder setWheels(int wheels) {
car.setWheels(wheels);
return this;
}
public CarBuilder setColor(String color) {
car.setColor(color);
return this;
}
public Car build() {
return car;
}
}
// Usage:
Car car = new CarBuilder()
.setEngine("V8")
.setWheels(4)
.setColor("Red")
.build();
This approach improves code readability and makes it easier to create objects with many parameters.