Sometimes an object needs extras, added in any mix. A class for every mix would soon mean dozens of classes.
The Decorator pattern wraps the object in another object that has the same methods. The wrapper does its own part and passes the call on to the object inside. Wrappers can stack in any order and in any number.
Here you price the drinks of a coffee shop. Each drink is an espresso, with milk or syrup as extras.
The interface Drink has two methods. Its cost() returns the price in cents. Its describe() returns the name of the drink. An interface lists the methods a class promises to have.
Write three classes:
Espresso()implementsDrink. It costs 250 cents, and its name is"espresso".Milk(drink)implementsDrinktoo. It wraps another drink and keeps it in a field. Itscost()is the inner drink's cost plus 50. Itsdescribe()is the inner drink's name followed by" + milk".Syrup(drink)works the same way. It adds 40 cents and" + syrup".
A wrapper is a Drink, and it holds a Drink. So the drink inside it can be another wrapper.
The tests build every drink themselves, wrapping it as they read the commands. They call cost() and describe() only on the outermost drink. So each wrapper must add its own part and pass the call on.
Each example is a list of commands, one per line:
espressostarts a new drink, a plain espresso.milkwraps the current drink in aMilk.syrupwraps the current drink in aSyrup.orderwrites the current drink'sdescribe(), a space and itscost(). After an order, the next extra still wraps the same drink.
Example 1:
Input: 1. espresso 2. order 3. milk 4. order 5. milk 6. syrup 7. order Output: espresso 250 espresso + milk 300 espresso + milk + milk + syrup 390 Explanation: Command 1 starts a plain espresso. It costs 250. Command 3 wraps it in milk, so it costs 250 + 50 = 300. Commands 5 and 6 wrap the same drink twice more. The milk adds 50 again and the syrup adds 40, so 390. The name lists the extras in the order they were added.
Example 2:
Input: 1. espresso 2. syrup 3. milk 4. order 5. espresso 6. milk 7. syrup 8. order 9. espresso 10. syrup 11. order Output: espresso + syrup + milk 340 espresso + milk + syrup 340 espresso + syrup 290 Explanation: The first two drinks have the same extras in another order. Their names differ, but both cost 250 + 40 + 50 = 340. Each espresso starts a new drink. So the last drink has only syrup, and it costs 290.
Constraints:
- Each example starts with
espresso. - A drink has at most 10 extras.
- There are at most 100,000 commands in all.
Note:
Each call should run in O(1) time. A drink has at most 10 extras, so a call passes through at most 11 objects.
Free plan: 30 tutor messages. PRO is unlimited.
