Decorator Pattern: Elegant Coupon System Design Without Class Explosion
The article demonstrates how the Decorator Pattern solves coupon stacking, order sensitivity, and class explosion problems in e-commerce by composing discount calculators recursively, with Java implementation examples and real-world JDK/Servlet references.
Problem Introduction
An e-commerce platform needs to support three coupon types: full-reduction (e.g., spend 100 reduce 20), voucher (direct deduction, capped at item price), and discount (percentage off). Coupons can stack across types and within the same type. The shopping cart must show original price, final price, and calculation breakdown.
Initial Approach and Its Failures
First attempt: create a calculator class for each combination (e.g., FullDiscountCalculator, VoucherDiscountCalculator, FullVoucherDiscountCalculator, etc.). With 3 coupon types this requires 7 classes. Adding a fourth type explodes to 15 classes — a classic class explosion.
Three concrete problems emerge:
Problem 1: Same-type stacking — Cannot represent two vouchers plus one full-reduction using fixed combination classes.
Problem 2: Class explosion — Number of classes grows geometrically with each new coupon type.
Problem 3: Order sensitivity — Applying full-reduction then discount yields different result than discount then full-reduction (example: 100 price, full-50-reduce-20, 30% off → 56 vs 50). Fixed combination classes cannot encode order.
Solution: Composition Over Inheritance + Recursive Delegation
Instead of inheritance, use composition. Each coupon calculator wraps a CostCalculator (the component interface) and delegates to it, adding its own logic. This forms a chain where each decorator receives the current price from the wrapped calculator, applies its rule, and passes the new price outward.
Key insights:
Same-type stacking solved: just wrap another voucher decorator.
No class explosion: only one class per coupon type, combined at runtime.
Order controlled by wrapping sequence: the chain order equals application order.
Implementation
Class Structure
CostCalculator(interface): description(),
finalCost()ShoppingCart(ConcreteComponent): holds goods, computes base sum. AbstractCostDecorator (Decorator): holds a calculator reference.
Concrete decorators: DiscountDecorator (percentage), FullDiscountDecorator (threshold + reduction), VoucherDecorator (flat amount).
Client Code Example
ShoppingCart cart = new ShoppingCart();
cart.addGoods(new GoodsDetail("T-shirt", 59.9, 2));
cart.addGoods(new GoodsDetail("Tennis racket", 100, 1));
cart.addGoods(new GoodsDetail("Mosquito repellent", 28.5, 2));
// Base price: 276.8
VoucherDecorator decorator = new VoucherDecorator(
new VoucherDecorator(
new FullDiscountDecorator(
new DiscountDecorator(cart, 0.85), 20, 100),
20),
5);
// Order: discount → full-reduction → voucher(20) → voucher(5)
System.out.println(decorator.finalCost()); // 190.28
System.out.println(decorator.description());
// "商品总费用 -> 8.5折扣 -> 满100减20 -> 20元抵用券 -> 5元抵用券"Execution Trace
Step 1: Base price = 276.80
Step 2: 8.5折 (discount 0.85) → 276.80 * 0.85 = 235.28
Step 3: 满100减20 (full-reduction) → 235.28 - 20 = 215.28
Step 4: 20元抵用券 (voucher) → 215.28 - 20 = 195.28
Step 5: 5元抵用券 (voucher) → 195.28 - 5 = 190.28
Decorator Pattern Essentials
Intent
Attach additional responsibilities to an object dynamically without altering its structure. Decorators provide a flexible alternative to subclassing for extending functionality.
Structure
Component — interface defining operations.
ConcreteComponent — base object (ShoppingCart).
Decorator — abstract class implementing Component, holding a Component reference.
ConcreteDecorator — adds specific behavior (DiscountDecorator, etc.).
Usage Tips
Omit abstract Decorator when only one ConcreteDecorator exists.
Keep Component interface minimal — no data storage. If Component is already heavy, consider Strategy pattern instead.
Real-World Examples in JDK
java.io.InputStream — BufferedInputStream, GZIPInputStream, DataInputStream all wrap another InputStream, adding buffering, decompression, primitive reading.
javax.servlet.ServletRequestWrapper — wraps ServletRequest to allow developers to extend request behavior (e.g., parameter modification, encoding changes).
Source code: https://github.com/i-tracy/patterns-for-me/blob/master/cases-structural/src/main/java/com/patterns/decorator
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
