Junior — Middle
Can you explain the principle of the 'Builder' pattern and its main application?
sobes.tech AI
Answer from AI
The "Builder" pattern is used for step-by-step creation of complex objects, separating the construction process from the representation. This allows creating different variants of an object using the same construction process.
The main idea is to have a separate class (builder) that accumulates parameters and steps for creating an object, and then returns the finished instance.
Application:
- When an object has many parameters, especially optional ones.
- When you need to create objects with different configurations.
Example in Swift:
class Car {
var color: String?
var seats: Int?
var engine: String?
}
class CarBuilder {
private var car = Car()
func setColor(_ color: String) -> CarBuilder {
car.color = color
return self
}
func setSeats(_ seats: Int) -> CarBuilder {
car.seats = seats
return self
}
func setEngine(_ engine: String) -> CarBuilder {
car.engine = engine
return self
}
func build() -> Car {
return car
}
}
// Usage:
// let car = CarBuilder().setColor("Red").setSeats(4).setEngine("V8").build()