1. Problem Complexity: Combinatorial Discounts
E-commerce carts support diverse promotional mechanics: Flat dollar discounts ($10 off), Percentage discounts (15% off cart), Category-specific discounts (20% off Shoes), and Buy-X-Get-Y rules.
The challenge lies in discount ordering, exclusivity rules (coupons that cannot be combined), and maximum cap limits.
2. Composite & Decorator Patterns for Discount Application
We model discounts using the Composite Pattern: a `Coupon` interface with an `applyDiscount(cart: Cart): number` method. A `CompositeDiscount` aggregates multiple rules, evaluating applicability in order of priority.
3. Code Implementation
Here is the clean object-oriented discount engine:
interface CartItem {
id: string;
price: number;
quantity: number;
category: string;
}
interface DiscountStrategy {
apply(cartTotal: number, items: CartItem[]): number;
}
class PercentageDiscount implements DiscountStrategy {
constructor(private percent: number, private maxCap: number) {}
apply(total: number): number {
const discount = (total * this.percent) / 100;
return Math.min(discount, this.maxCap);
}
}
class FlatDiscount implements DiscountStrategy {
constructor(private flatAmount: number, private minThreshold: number) {}
apply(total: number): number {
return total >= this.minThreshold ? this.flatAmount : 0;
}
}Model this architecture on the HLDForge Canvas
Turn static box diagrams into living, collaborative systems. Drag and drop microservices, Kafka clusters, and cache tiers. Run automated SPOF detection and STRIDE threat modeling in real time.
Written by HLDForge Architecture Team
Lead Machine Coding Specialist
The HLDForge Architecture Team publishes practical engineering guides, real-world case studies, and high-concurrency blueprints to help engineers build scalable and fault-tolerant software.