Amazon OOD:结账价格引擎(三种折扣)
给购物车行项目和客户等级,应用百分比折扣、固定金额折扣、买 X 送 Y,返回小计、总价和已应用折扣列表。
2025-05OAVO Helper · 面经整理
01 · QUESTIONS
面试题目
- 给购物车行项目和客户等级,应用百分比折扣、固定金额折扣、买 X 送 Y,返回小计、总价和已应用折扣列表
02 · FOLLOW-UPS
追问
- 新增折扣类型要改哪里
03 · ANSWERS
参考答案
用策略模式(Strategy)把每种折扣抽象成一个 Discount,价格引擎只负责按顺序应用;新增折扣类型不需要改引擎。
需求澄清(先问清楚再设计)
- 多个折扣的叠加顺序是什么、是否互斥;百分比折扣基于折扣前还是折扣后的价格。
- 金额的表示:用整数「分」,避免浮点误差;百分比折扣的舍入规则。
- 客户等级是否限制可用的折扣;返回值需要小计、总价和已应用折扣列表(名称 + 金额)。
核心类
LineItem(sku、单价、数量)、AppliedDiscount(名称、金额)、PricingResult(小计、总价、已应用列表)。Discount抽象基类:eligible(tier)判断客户等级是否适用,amount(items, current_total)返回应减金额。PercentOff/FixedOff/BuyXGetY三个子类各管自己的计算规则。PricingEngine:持有有序折扣列表,依次应用,记录实际生效的折扣。
代码
from abc import ABC, abstractmethod
from dataclasses import dataclass
@dataclass(frozen=True)
class LineItem:
sku: str
unit_price: int # 单位:分,用整数避免浮点误差
qty: int
@dataclass(frozen=True)
class AppliedDiscount:
name: str
amount: int
@dataclass
class PricingResult:
subtotal: int
total: int
applied: list
class Discount(ABC):
def __init__(self, name, tiers=None):
self.name, self.tiers = name, tiers # tiers=None:所有客户等级都适用
def eligible(self, tier):
return self.tiers is None or tier in self.tiers
@abstractmethod
def amount(self, items, current_total): # 返回应减去的金额(分)
...
class PercentOff(Discount):
def __init__(self, name, percent, tiers=None):
super().__init__(name, tiers); self.percent = percent
def amount(self, items, current_total):
return current_total * self.percent // 100
class FixedOff(Discount):
def __init__(self, name, off, tiers=None):
super().__init__(name, tiers); self.off = off
def amount(self, items, current_total):
return min(self.off, current_total) # 不会把总价减成负数
class BuyXGetY(Discount):
def __init__(self, name, sku, buy, free, tiers=None):
super().__init__(name, tiers); self.sku, self.buy, self.free = sku, buy, free
def amount(self, items, current_total):
off = sum((it.qty // (self.buy + self.free)) * self.free * it.unit_price
for it in items if it.sku == self.sku)
return min(off, current_total)
class PricingEngine:
def __init__(self, discounts):
self.discounts = discounts # 列表顺序 = 叠加顺序
def price(self, items, tier):
subtotal = sum(it.unit_price * it.qty for it in items)
total, applied = subtotal, []
for d in self.discounts:
if not d.eligible(tier):
continue
off = d.amount(items, total)
if off > 0:
total -= off
applied.append(AppliedDiscount(d.name, off))
return PricingResult(subtotal, total, applied)设计要点
- 「折扣规则」与「编排流程」分离:规则变化只动子类,叠加顺序只动引擎的配置。
- 总价用
min兜底,保证不会出现负数;金额统一为整数分。 - 买 X 送 Y 按 SKU 的每 (X+Y) 件为一组,每组免 Y 件;未满一组的不享受。
追问解答
新增折扣类型要改哪里
- 只需新增一个
Discount子类,并把它加入PricingEngine的折扣列表;引擎和已有折扣都不用改(开闭原则)。 - 唯一会波及已有类的情形是:新折扣需要额外上下文(如优惠码、时间、地区)。预防办法是
amount接收一个 context 对象,而不是一串零散参数,之后扩展只加字段。 - 互斥、叠加上限这类规则放在引擎配置里,而不是写进各个折扣子类。
联系 OAVO Helper
想针对这题做模拟练习?
加微信 aasummer 咨询陪跑,我们可以按你的目标岗位安排简历、模拟面试或代投。
加微信 aasummer 咨询陪跑微信:aasummer