Introduction
The last article examined the general case of using the Builder pattern, but the option was not touched upon when the object is created in stages in time.
Builder pattern (builder) is a generating design template that allows you to gradually create complex objects. It is especially useful when the object has many parameters or various configurations. One of the interesting examples of its use is the ability to separate the process of creating an object in time.
Sometimes the object cannot be created immediately – its parameters can become known at different stages of the program.
An example on Python
In this example, the object of the car is created in stages: first, part of the data is loaded from the server, then the user enters the missing information.
import requests
def fetch_car_data():
response = requests.get("https://api.example.com/car-info")
return response.json()
builder = CarBuilder()
# Backend API data
car_data = fetch_car_data()
builder.set_model(car_data["model"])
builder.set_year(car_data["year"])
# User input
color = input("Car color: ")
builder.set_color(color)
gps_option = input("GPS feature? (yes/no): ").lower() == "yes"
builder.set_gps(gps_option)
car = builder.build()
print(car)
Imagine an API call, data entry occur in different parts of the application, or even in different libraries. Then the use of the Builder pattern becomes more obvious than in a simple example above.
Advantages
– the output is an immune structure that does not need to store optional data for temporary assembly
– The object is collected gradually
– avoiding complex designers
– The assembly code of the object is incomplinge only in one essence of Builder
– Convenience of understanding code
Sources
https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional-ebook/dp/B000SEIBB8
https://demensdeum.com/blog/2019/09/23/builder-pattern/