|
| 1 | +# Define a Pizza interface |
| 2 | +from abc import abstractmethod |
| 3 | + |
| 4 | + |
| 5 | +class Pizza: |
| 6 | + @abstractmethod |
| 7 | + def prepare(self): |
| 8 | + return "Concrete implementation required" |
| 9 | + |
| 10 | + |
| 11 | + @abstractmethod |
| 12 | + def bake(self): |
| 13 | + pass |
| 14 | + |
| 15 | + @abstractmethod |
| 16 | + def cut(self): |
| 17 | + pass |
| 18 | + |
| 19 | + @abstractmethod |
| 20 | + def box(self): |
| 21 | + pass |
| 22 | + |
| 23 | +# Concrete Pizza classes |
| 24 | +class MargheritaPizza(Pizza): |
| 25 | + |
| 26 | + def prepare(self): |
| 27 | + print("Preparing Margherita Pizza") |
| 28 | + |
| 29 | + def bake(self): |
| 30 | + print("Baking Margherita Pizza") |
| 31 | + |
| 32 | + def cut(self): |
| 33 | + print("Cutting Margherita Pizza") |
| 34 | + |
| 35 | + def box(self): |
| 36 | + print("Boxing Margherita Pizza") |
| 37 | + |
| 38 | +class PepperoniPizza(Pizza): |
| 39 | + def prepare(self): |
| 40 | + print("Preparing Pepperoni Pizza") |
| 41 | + |
| 42 | + def bake(self): |
| 43 | + print("Baking Pepperoni Pizza") |
| 44 | + |
| 45 | + def cut(self): |
| 46 | + print("Cutting Pepperoni Pizza") |
| 47 | + |
| 48 | + def box(self): |
| 49 | + print("Boxing Pepperoni Pizza") |
| 50 | + |
| 51 | +# Pizza Factory |
| 52 | +class PizzaFactory: |
| 53 | + """It creates and returns an instance of the appropriate subclass based |
| 54 | + on the pizza_type parameter.""" |
| 55 | + def create_pizza(self, pizza_type): |
| 56 | + if pizza_type == 'Margherita': |
| 57 | + return MargheritaPizza() |
| 58 | + elif pizza_type == 'Pepperoni': |
| 59 | + return PepperoniPizza() |
| 60 | + else: |
| 61 | + raise ValueError("Invalid pizza type") |
| 62 | + |
| 63 | +# Client code |
| 64 | +if __name__ == "__main__": |
| 65 | + # Creating a Margherita Pizza using the factory |
| 66 | + factory = PizzaFactory() |
| 67 | + margherita_pizza = factory.create_pizza('Margherita') |
| 68 | + |
| 69 | + # Using the created Margherita Pizza |
| 70 | + margherita_pizza.prepare() |
| 71 | + margherita_pizza.bake() |
| 72 | + margherita_pizza.cut() |
| 73 | + margherita_pizza.box() |
| 74 | + |
| 75 | + # Creating a Pepperoni Pizza using the factory |
| 76 | + pepperoni_pizza = factory.create_pizza('Pepperoni') |
| 77 | + |
| 78 | + # Using the created Pepperoni Pizza |
| 79 | + pepperoni_pizza.prepare() |
| 80 | + pepperoni_pizza.bake() |
| 81 | + pepperoni_pizza.cut() |
| 82 | + pepperoni_pizza.box() |
0 commit comments