装饰器模式 电商 案例
时间: 2024-01-01 14:48:06 浏览: 23
装饰器模式是一种结构型设计模式,它允许你通过将对象放入包装器类中来为原对象动态地添加新的行为。这种模式可以有效地扩展对象的功能,同时保持代码的可读性和可维护性。
在电商中,装饰器模式可以用于实现购物车功能。购物车可以添加商品、删除商品、调整商品数量等操作,同时还可以计算商品总价和应付金额等信息。这些操作可以通过装饰器模式来实现。
首先,我们定义一个商品类,表示电商中的商品:
```python
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
```
然后,我们定义一个购物车类,用于管理商品列表:
```python
class ShoppingCart:
def __init__(self):
self.products = []
def add_product(self, product):
self.products.append(product)
def remove_product(self, product):
self.products.remove(product)
def get_total_price(self):
return sum(product.price for product in self.products)
def get_checkout_amount(self):
return self.get_total_price()
```
现在,我们可以使用装饰器模式来扩展购物车功能。例如,我们可以为购物车添加折扣功能:
```python
class DiscountDecorator:
def __init__(self, component, discount):
self.component = component
self.discount = discount
def get_total_price(self):
return self.component.get_total_price() * (1 - self.discount)
def get_checkout_amount(self):
return self.get_total_price()
```
这个装饰器类接受一个购物车对象和一个折扣参数,用于计算打折后的总价。
我们还可以为购物车添加优惠券功能:
```python
class CouponDecorator:
def __init__(self, component, coupon):
self.component = component
self.coupon = coupon
def get_total_price(self):
return self.component.get_total_price() - self.coupon
def get_checkout_amount(self):
return self.get_total_price()
```
这个装饰器类接受一个购物车对象和一个优惠券参数,用于计算优惠后的总价。
使用装饰器模式,我们可以方便地为购物车添加各种功能,而不需要修改原有的购物车类。例如,我们可以这样使用购物车:
```python
# 创建购物车对象
cart = ShoppingCart()
# 添加商品
cart.add_product(Product("iPhone", 8000))
cart.add_product(Product("MacBook", 12000))
# 使用折扣装饰器
cart = DiscountDecorator(cart, 0.9)
# 使用优惠券装饰器
cart = CouponDecorator(cart, 1000)
# 输出应付金额
print(cart.get_checkout_amount()) # 16100.0
```
这个例子展示了如何使用装饰器模式来为电商中的购物车功能添加折扣和优惠券功能。通过使用装饰器模式,我们可以方便地扩展购物车功能,同时保持代码的可读性和可维护性。