Composite Pattern
# Represents a single product
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def getPrice(self):
return self.price
def display(self, indent):
print(f"{indent}Product: {self.name} – ₹{self.price}")
# Represents a bundle of products
class ProductBundle:
def __init__(self, bundleName):
self.bundleName = bundleName
self.products = []
def addProduct(self, product):
self.products.append(product)
def getPrice(self):
return sum(product.getPrice() for product in self.products)
def display(self, indent):
print(f"{indent}Bundle: {self.bundleName}")
for product in self.products:
product.display(indent + " ")
# Main logic
if __name__ == "__main__":
# Individual Items
book = Product("Book", 500)
headphones = Product("Headphones", 1500)
charger = Product("Charger", 800)
pen = Product("Pen", 20)
notebook = Product("Notebook", 60)
# Bundle: iPhone Combo
iphoneCombo = ProductBundle("iPhone Combo Pack")
iphoneCombo.addProduct(headphones)
iphoneCombo.addProduct(charger)
# Bundle: School Kit
schoolKit = ProductBundle("School Kit")
schoolKit.addProduct(pen)
schoolKit.addProduct(notebook)
# Add to cart logic
cart = [book, iphoneCombo, schoolKit]
# Display Cart
total = 0
print("Cart Details:\n")
for item in cart:
if isinstance(item, Product):
item.display(" ")
total += item.getPrice()
elif isinstance(item, ProductBundle):
item.display(" ")
total += item.getPrice()
print(f"\nTotal Price: ₹{total}")

Last updated