Discount strategy
Interchangeable discount algorithms in a checkout: percentage, threshold and "best of", swapped at runtime.
Checkout computes the order total, while the discount comes from a strategy passed in from outside. Marketing can add new promotions without touching the checkout code.
Task
PercentageDiscount(percent)– lowers the price by a percentage; a percentage outside 0–100 → exception (ValueErrorin Python,Error('Percent must be between 0 and 100')in TypeScript).ThresholdDiscount(threshold, amount)– fromthresholdon, subtractsamount, never below zero.BestDiscount(...strategies)– applies whichever strategy gives the lowest price (a strategy composed of strategies).Checkout.total(items)– sum ofprice × quantity, then the strategy, rounded to cents;set_strategy/setStrategyswaps the strategy at runtime.
| Cart | Strategy | Result |
|---|---|---|
| 2 × 100 + 1 × 50 | 10% | 225.00 |
| 2 × 100 + 1 × 50 | 30 off from 200 | 220.00 |
| 9.99 | 33% | 6.69 |
Topics: Strategy