Design PatternsL3 · Medium
Decorator Pattern: Coffee Customisation
Problem
Design a coffee ordering system where a base Coffee can be decorated with add-ons (Milk, Sugar, Whip, VanillaSyrup) at runtime. Each add-on wraps the base object, adding to the cost and description — without creating a class explosion of MilkSugarWhipCoffee, MilkCoffee, etc.
Requirements
- Coffee interface with: getDescription(): string, getCost(): number
- SimpleCoffee (base): 'Coffee', ₹50
- MilkDecorator: wraps any Coffee, adds 'Milk' to description, +₹15
- SugarDecorator: wraps any Coffee, adds 'Sugar', +₹5
- WhipDecorator: wraps any Coffee, adds 'Whip', +₹20
- Show: SimpleCoffee → add Milk → add Whip → add Sugar = correct total and description
- Decorators can be stacked in any order
Constraints
- –No subclass for each combination (no MilkWhipCoffee class)
- –Each decorator must accept ANY Coffee (including another decorator)
✓ Saved