電商平台面試中的經典系統設計題。本文通過促銷規則引擎設計,展示如何構建靈活可擴展的業務規則系統,oavoservice 助你掌握電商核心技術。
📋 業務場景
設計一個促銷規則引擎,支援:
- 滿減(滿1000減100)
- 折扣(8折優惠)
- 買N送M(買2送1)
- 組合優惠(A+B一起買打折)
- 規則優先級和互斥
🎯 設計目標
- 靈活性 - 易於添加新規則類型
- 可組合 - 支援規則組合
- 高效能 - 快速計算最優方案
- 可維護 - 清晰的程式碼結構
💡 系統設計(oavoservice 方案)
規則抽象
from abc import ABC, abstractmethod
from enum import Enum
class PromotionType(Enum):
DISCOUNT = "discount"
FULL_REDUCTION = "full_reduction"
BUY_N_GET_M = "buy_n_get_m"
COMBO = "combo"
class Promotion(ABC):
def __init__(self, promotion_id, name, priority=0):
self.id = promotion_id
self.name = name
self.priority = priority
self.exclusive_with = [] # 互斥規則
@abstractmethod
def can_apply(self, cart):
pass
@abstractmethod
def calculate_discount(self, cart):
pass
@abstractmethod
def apply(self, cart):
pass
class DiscountPromotion(Promotion):
def __init__(self, promotion_id, name, discount_rate,
applicable_products=None):
super().__init__(promotion_id, name)
self.discount_rate = discount_rate
self.applicable_products = applicable_products or []
def can_apply(self, cart):
if not self.applicable_products:
return True
return any(item.product_id in self.applicable_products
for item in cart.items)
def calculate_discount(self, cart):
total = 0
for item in cart.items:
if (not self.applicable_products or
item.product_id in self.applicable_products):
total += item.price * item.quantity
return total * (1 - self.discount_rate)
def apply(self, cart):
discount = self.calculate_discount(cart)
cart.add_discount(self.name, discount)
return cart
購物車模型
class ShoppingCart:
def __init__(self):
self.items = []
self.discounts = []
self.applied_promotions = set()
def add_item(self, item):
# 實作添加商品邏輯
pass
def get_total(self):
return sum(item.get_subtotal() for item in self.items)
def add_discount(self, name, amount):
self.discounts.append({'name': name, 'amount': amount})
def get_final_price(self):
total = self.get_total()
total_discount = sum(d['amount'] for d in self.discounts)
return max(0, total - total_discount)
促銷引擎
class PromotionEngine:
def __init__(self):
self.promotions = []
def add_promotion(self, promotion):
self.promotions.append(promotion)
self.promotions.sort(key=lambda p: p.priority, reverse=True)
def calculate_best_promotions(self, cart):
# 使用動態規劃或剪枝搜尋找到最優方案
pass
💼 oavoservice 助力
設計模式 - 策略模式和工廠模式 業務抽象 - 靈活的規則系統 性能優化 - 最優方案計算 擴展性 - 易於添加新規則
聯繫 oavoservice,專業電商系統面試輔助!
標籤: #電商 #促銷引擎 #系統設計 #設計模式 #VO輔助 #面試輔助 #一畝三分地
需要面試真題? 立刻聯繫微信 Coding0201,獲得真題。