Facebook Pixel

Exercise: Decorator

This exercise puts the Decorator pattern into code.

Scenario

A coffee shop menu has two base beverages and three toppings that can be added in any combination. A Beverage interface exposes cost() (an integer) and description() (a string). Two concrete beverages implement it: Espresso costs 3 and Drip costs 2. Three topping decorators each wrap a BeverageMilk adds 1, Mocha adds 2, and Whip adds

  1. Each decorator delegates to the wrapped beverage and then appends its own contribution, so cost and description flow through the entire chain.

Commands

CommandBehaviorOutput
["base", type]Start a fresh beverage ("espresso" or "drip")(none)
["add", topping]Wrap the current beverage in the named decorator ("milk", "mocha", or "whip")(none)
["cost"]Output the total cost of the current drink"Cost: <total>"
["desc"]Output the description of the current drinke.g. "espresso + milk + mocha"
Example
Input
7
base espresso
add milk
cost
add mocha
add whip
cost
desc
Output
Cost: 4
Cost: 7
espresso + milk + mocha + whip
Explanation
The base espresso costs 3. After adding milk (+1) the cost is 4, confirmed by the first `cost` command. Two more toppings are then stacked — mocha (+2) and whip (+1) — bringing the total to 7. The final `desc` command walks the entire chain from innermost to outermost, producing `"espresso + milk + mocha + whip"`. Note that `base` and `add` produce no output; only `cost` and `desc` print a line.

Your task

Create the two base beverages (Espresso and Drip, both extend Beverage) and the three toppings (Milk, Mocha, and Whip, all extend ToppingDecorator) so the commands produce the output described above. The starter keeps Beverage and ToppingDecorator and marks where to add the concrete classes with a TODO comment listing each class's signatures and return values.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro