The builder pattern can be used for constructing complex objects with many configurable options.
The benefit of the Builder Pattern is that it allows for the creation of complex objects step by step, providing a clear and flexible way to configure and construct objects with varying attributes and options.
class Pizza:
def __init__(self):
self.size = None
self.cheese = False
self.pepperoni = False
self.bacon = False
def __str__(self):
toppings = []
if self.cheese:
toppings.append("cheese")
if self.pepperoni:
toppings.append("pepperoni")
if self.bacon:
toppings.append("bacon")
return f"Size: {self.size}, Toppings: {', '.join(toppings)}"
class PizzaBuilder:
def __init__(self):
self.pizza = Pizza()
def set_size(self, size):
self.pizza.size = size
return self
def add_cheese(self):
self.pizza.cheese = True
return self
def add_pepperoni(self):
self.pizza.pepperoni = True
return self
def add_bacon(self):
self.pizza.bacon = True
return self
def build(self):
return self.pizza
# Client code
builder = PizzaBuilder()
pizza = builder.set_size("Large").add_cheese().add_pepperoni().build()
print(pizza)