|
| 1 | +# Composite Pattern Python Implementation: Products and Boxes |
| 2 | + |
| 3 | +from abc import ABC, abstractmethod |
| 4 | + |
| 5 | + |
| 6 | +# Component Interface |
| 7 | + |
| 8 | +class Item(ABC): |
| 9 | + @abstractmethod |
| 10 | + def get_price(self): |
| 11 | + ... |
| 12 | + |
| 13 | + @abstractmethod |
| 14 | + def get_description(self): |
| 15 | + ... |
| 16 | + |
| 17 | + |
| 18 | +# Leaf Class: Product |
| 19 | + |
| 20 | +class Product(Item): |
| 21 | + def __init__(self, name, price): |
| 22 | + self.name = name |
| 23 | + self.price = price |
| 24 | + |
| 25 | + def get_price(self): |
| 26 | + return self.price |
| 27 | + |
| 28 | + def get_description(self): |
| 29 | + return f"Product: {self.name} (${self.price})" |
| 30 | + |
| 31 | + |
| 32 | +# Composite Class: Box |
| 33 | + |
| 34 | +class Box(Item): |
| 35 | + def __init__(self, name): |
| 36 | + self.name = name |
| 37 | + self.items = [] |
| 38 | + |
| 39 | + def add(self, item: Item): |
| 40 | + self.items.append(item) |
| 41 | + |
| 42 | + def remove(self, item: Item): |
| 43 | + self.items.remove(item) |
| 44 | + |
| 45 | + def get_price(self): |
| 46 | + total = 0 |
| 47 | + |
| 48 | + for item in self.items: |
| 49 | + total += item.get_price() |
| 50 | + return total |
| 51 | + |
| 52 | + def get_description(self): |
| 53 | + description = [item.get_description() for item in self.items] |
| 54 | + return f"Box: {self.name} containing:\n " + "\n ".join(description) |
| 55 | + |
| 56 | + |
| 57 | +# client Code |
| 58 | + |
| 59 | +if __name__ == "__main__": |
| 60 | + # Leaf Products |
| 61 | + pen = Product("Pen", 2.5) |
| 62 | + notebook = Product("Notebook", 5.0) |
| 63 | + charger = Product("Charger", 15.0) |
| 64 | + |
| 65 | + # Small Box |
| 66 | + small_box = Box("Stationary Box") |
| 67 | + small_box.add(pen) |
| 68 | + small_box.add(notebook) |
| 69 | + |
| 70 | + # Another box |
| 71 | + |
| 72 | + electronics_box = Box("Electronics Box") |
| 73 | + electronics_box.add(charger) |
| 74 | + |
| 75 | + # Big Box |
| 76 | + |
| 77 | + main_box = Box("Main Box") |
| 78 | + main_box.add(small_box) |
| 79 | + main_box.add(electronics_box) |
| 80 | + main_box.add(Product("USB Drive", 8.0)) |
| 81 | + |
| 82 | + print(main_box.get_description()) |
| 83 | + print(f"Total Price: ${main_box.get_price()}") |
0 commit comments