Skip to content

Instantly share code, notes, and snippets.

@robson-koji
Created June 26, 2023 20:11
Show Gist options
  • Save robson-koji/a18e41b484dd1570a8b3cb0688bbf965 to your computer and use it in GitHub Desktop.
Save robson-koji/a18e41b484dd1570a8b3cb0688bbf965 to your computer and use it in GitHub Desktop.
Design Pattern - Builder

Builder

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment