Bird
Raised Fist0

What is the output of print(coffee.cost()) when coffee is wrapped with two decorators, one adding 0 cost and another adding 2?

medium🧾 Code Trace Q4 of Q15
OOP & Design Patterns - Decorator Pattern - Wrapping Behaviour Without Subclassing
Consider the following code snippet using the Decorator Pattern. What is the output of print(coffee.cost()) when coffee is wrapped with two decorators, one adding 0 cost and another adding 2? ```python class SimpleCoffee: def cost(self): return 5 class MilkDecorator: def __init__(self, coffee): self._coffee = coffee def cost(self): return self._coffee.cost() + 0 class SugarDecorator: def __init__(self, coffee): self._coffee = coffee def cost(self): return self._coffee.cost() + 2 coffee = SugarDecorator(MilkDecorator(SimpleCoffee())) print(coffee.cost()) ```
A5
B0
C2
D7
Step-by-Step Solution
Solution:
  1. Step 1: Trace inner decorator MilkDecorator.cost()

    MilkDecorator calls SimpleCoffee.cost() returning 5, adds 0 -> 5.
  2. Step 2: Trace outer decorator SugarDecorator.cost()

    SugarDecorator calls MilkDecorator.cost() returning 5, adds 2 -> 7.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Stacked decorators add costs cumulatively [OK]
Quick Trick: Decorator cost sums from innermost to outermost [OK]
Common Mistakes:
MISTAKES
  • Ignoring inner decorator cost
  • Adding costs in wrong order
  • Returning only outer decorator cost
Trap Explanation:
PITFALL
  • Candidates often forget to accumulate costs through all decorators.
Interviewer Note:
CONTEXT
  • Tests understanding of call delegation and accumulation in stacked decorators.
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