Bird
Raised Fist0

Given the following Python code using the Decorator Pattern, what is the output of print(coffee.description()) and print(coffee.cost()) after wrapping a SimpleCoffee with MilkDecorator (amount=2) and then SugarDecorator (amount=1)?

easy🧾 Code Trace Q12 of Q15
OOP & Design Patterns - Decorator Pattern - Wrapping Behaviour Without Subclassing
Given the following Python code using the Decorator Pattern, what is the output of print(coffee.description()) and print(coffee.cost()) after wrapping a SimpleCoffee with MilkDecorator (amount=2) and then SugarDecorator (amount=1)?
ACoffee, Milk(2), Sugar(1) 6.3
BCoffee, Sugar(1), Milk(2) 5.8
CCoffee, Sugar(1), Milk(2) 6.3
DCoffee, Milk(2), Sugar(1) 5.8
Step-by-Step Solution
  1. Step 1: Trace description calls

    Starting from SugarDecorator: description() calls MilkDecorator.description(), which calls SimpleCoffee.description() returning "Coffee". Then MilkDecorator adds ", Milk(2)", SugarDecorator adds ", Sugar(1)" -> "Coffee, Milk(2), Sugar(1)".
  2. Step 2: Trace cost calls

    SimpleCoffee.cost() = 5. MilkDecorator adds 0.5 * 2 = 1. SugarDecorator adds 0.3 * 1 = 0.3. Total cost = 5 + 1 + 0.3 = 6.3.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Description order matches wrapping order; cost sums correctly [OK]
Quick Trick: Decorator calls chain in wrapping order [OK]
Common Mistakes:
MISTAKES
  • Mixing order of decorators in description
  • Forgetting to multiply cost by amount
Trap Explanation:
PITFALL
  • Candidates often confuse the order of decorator calls or forget to accumulate costs properly.
Interviewer Note:
CONTEXT
  • Tests ability to mentally execute decorator chaining and accumulation.
Master "Decorator Pattern - Wrapping Behaviour Without Subclassing" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes