Providing a step-by-step approach to build complex objects effortlessly
In essence, the builder Design Pattern simplifies and organizes the creation of complex objects, offering a step-by-step approach with flexibility and clarity. It’s like having a skilled architect guide you through building your perfect object, brick by brick.
class Product:
def __init__(self):
self.parts = []
def add(self, part):
self.parts.append(part)
def list_parts(self):
print("Product parts:")
for part in self.parts:
print(part)
class Builder:
def __init__(self):
self.product = Product()
def build_part_a(self):
self.product.add("Part A")
return self # Allow chaining
def build_part_b(self):
self.product.add("Part B")
return self # Allow chaining
def build_part_c(self):
self.product.add("Part C")
return self # Allow chaining
def get_product(self):
return self.product
# Client code
builder = Builder()
product = builder.build_part_a().build_part_c().get_product() # Chaining calls
product.list_parts() # Output:
# Product parts:
# Part A
# Part C