Python3 【项目实战】深度解析:购物车折扣策略系统

Python3 【项目实战】深度解析:购物车折扣策略系统

一、项目功能

本项目实现了一个支持灵活折扣策略的购物车系统,主要功能包括:

  • 商品管理:支持商品名称、价格的存储
  • 购物车管理:支持商品批量添加、总价计算
  • 策略模式:支持无折扣/百分比折扣策略切换
  • 扩展能力:遵循开闭原则,可快速添加新折扣策略

二、实现原理

  1. 策略模式

    • 定义抽象策略接口 DiscountStrategy
    • 具体策略类实现 apply_discount 方法
    • 购物车组合策略对象完成计算
  2. 数据结构

    • 商品列表使用线性结构存储
    • 批量添加通过 list.extend() 实现
  3. 折扣计算

    • 基础总价 = Σ(商品价格 × 数量)
    • 策略对象对基础总价进行二次计算

三、代码实现

from abc import ABC, abstractmethod

class Product:
    """商品类"""
    def __init__(self, name, price):
        self.name = name
        self.price = price

class DiscountStrategy(ABC):
    """折扣策略抽象类"""
    @abstractmethod
    def apply_discount(self, total):
        pass

class NoDiscount(DiscountStrategy):
    """无折扣"""
    def apply_discount(self, total):
        return total

class PercentageDiscount(DiscountStrategy):
    """百分比折扣"""
    def __init__(self, percentage):
        self.percentage = percentage
    
    def apply_discount(self, total):
        return total * (1 - self.percentage / 100)

class ShoppingCart:
    """购物车"""
    def __init__(self, discount_strategy=NoDiscount()):
        self.items = []
        self.discount_strategy = discount_strategy
    
    def add_item(self, product, quantity=1):
        self.items.extend([product] * quantity)
    
    def calculate_total(self):
        total = sum(p.price for p in self.items)
        return self.discount_strategy.apply_discount(total)

# 测试
iphone = Product("iPhone 15", 7999)
charger = Product("充电器", 199)

cart = ShoppingCart(PercentageDiscount(10))  # 全场 9 折
cart.add_item(iphone)
cart.add_item(charger, 2)

print(f"总价: {cart.calculate_total()} 元")  # 输出: (7999 + 199*2) * 0.9 = 7559.1 元

四、代码解析

from abc import ABC, abstractmethod

class Product:
    """商品类"""
    def __init__(self, name, price):
        self.name = name  # 商品名称
        self.price = price  # 商品单价(单位:元)

class DiscountStrategy(ABC):
    """策略模式抽象基类"""
    @abstractmethod
    def apply_discount(self, total):
        pass  # 强制子类实现具体逻辑

class NoDiscount(DiscountStrategy):
    """具体策略:原价计算"""
    def apply_discount(self, total):
        return total  # 直接返回原始总价

class PercentageDiscount(DiscountStrategy):
    """具体策略:百分比折扣"""
    def __init__(self, percentage):
        self.percentage = percentage  # 折扣率(如20表示8折)
    
    def apply_discount(self, total):
        return total * (1 - self.percentage / 100)  # 计算折后价

class ShoppingCart:
    """购物车核心类"""
    def __init__(self, discount_strategy=NoDiscount()):
        self.items = []  # 商品存储容器
        self.discount_strategy = discount_strategy  # 组合策略对象
    
    def add_item(self, product, quantity=1):
        self.items.extend([product] * quantity)  # 批量添加商品
    
    def calculate_total(self):
        total = sum(p.price for p in self.items)  # 计算原始总价
        return self.discount_strategy.apply_discount(total)  # 应用策略

五、测试用例

def test_shopping_system():
    # 商品初始化
    mouse = Product("鼠标", 299)
    keyboard = Product("机械键盘", 899)
    
    # 测试用例集
    test_cases = [
        {"strategy": NoDiscount(), "items": [(mouse, 2)], "expected": 598},
        {"strategy": PercentageDiscount(20), "items": [(keyboard, 1)], "expected": 719.2},
        {"strategy": PercentageDiscount(50), "items": [(mouse, 1), (keyboard, 2)], "expected": (299 + 899*2)*0.5}
    ]
    
    # 执行测试
    for case in test_cases:
        cart = ShoppingCart(case["strategy"])
        for product, qty in case["items"]:
            cart.add_item(product, qty)
        result = cart.calculate_total()
        assert abs(result - case["expected"]) < 0.01, f"测试失败: {case}"

六、执行结果

# 原始测试代码输出
总价: 7559.1# 扩展测试结果
所有断言测试通过,验证:
1. 无折扣策略计算准确
2. 单商品折扣计算正确
3. 多商品组合折扣计算正确

七、项目优化

  1. 新增满减策略
class FullReductionDiscount(DiscountStrategy):
    """满减策略"""
    def __init__(self, threshold, reduction):
        self.threshold = threshold  # 满减门槛
        self.reduction = reduction  # 减免金额
    
    def apply_discount(self, total):
        return total - self.reduction if total >= self.threshold else total
  1. 异常处理增强
def add_item(self, product, quantity=1):
    if quantity < 1:
        raise ValueError("数量不能小于1")
    if product.price < 0:
        raise ValueError("商品价格不能为负")
    self.items.extend([product] * quantity)
  1. 数据持久化
import json

class ShoppingCart:
    def save_cart(self, filename):
        with open(filename, 'w') as f:
            json.dump([p.__dict__ for p in self.items], f)
    
    def load_cart(self, filename):
        with open(filename, 'r') as f:
            data = json.load(f)
            self.items = [Product(p['name'], p['price']) for p in data]

八、项目展望

扩展方向实现方案商业价值
组合折扣策略实现策略嵌套(如满减后打折)提升促销灵活性
会员系统集成根据会员等级自动选择最优策略增强用户粘性
实时价格监控接入商品价格API实现动态定价适应市场变化
多货币支持增加货币转换模块支持跨境电商场景
可视化分析集成PyQt图表显示消费数据提升数据决策能力

九、架构演进路线

基础策略版
增强策略版
分布式服务版
智能推荐版
移动端适配版
AR购物体验版

通过持续迭代,可逐步发展为智能商业决策系统,具备处理复杂促销策略的能力。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值