Junior — Middle
Can you explain the working principle and main ideas of the Builder pattern?
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 presentation. It is convenient when an object has many parameters, some of which are optional.
Main ideas:
- A separate Builder class is created, which contains methods for setting parameters.
- Builder methods return the Builder itself, allowing for method chaining (fluent interface).
- At the end, the build() method is called, which returns the finished object.
Example in Python:
class Car:
def __init__(self, color=None, engine=None, seats=None):
self.color = color
self.engine = engine
self.seats = seats
class CarBuilder:
def __init__(self):
self.color = None
self.engine = None
self.seats = None
def set_color(self, color):
self.color = color
return self
def set_engine(self, engine):
self.engine = engine
return self
def set_seats(self, seats):
self.seats = seats
return self
def build(self):
return Car(self.color, self.engine, self.seats)
Usage: builder = CarBuilder() car = builder.set_color('red').set_engine('V8').set_seats(4).build()
This approach improves code readability and simplifies the creation of objects with many parameters.