MediumTypeScript

Decorator

TypeScriptDesign PatternsStructuralDecorator

Attach new behavior to an object dynamically, by wrapping it, instead of subclassing every combination (CoffeeWithMilk, CoffeeWithMilkAndSugar, ...).

Implement `MilkDecorator`/`SugarDecorator`, each wrapping a Coffee and adding to its cost()/description().

solve(addons) wraps a SimpleCoffee (cost 2, description 'Coffee') with one decorator per addon, in order, and returns the final { cost, description }.

solve(['milk', 'sugar']){ cost: 2.75, description: 'Coffee + Milk + Sugar' }

Sample tests

Test #1No addons
Input: [[]]
Output: {"cost":2,"description":"Coffee"}
Test #2Milk only
Input: [["milk"]]
Output: {"cost":2.5,"description":"Coffee + Milk"}
Test #3Milk then sugar, stacked
Input: [["milk","sugar"]]
Output: {"cost":2.75,"description":"Coffee + Milk + Sugar"}