Bird
0
0

When implementing a vending machine with the State pattern, how should the transition from 'WaitingForSelection' to 'Dispensing' state be handled after a user selects a product?

hard📝 Trade-off Q8 of 15
LLD - Behavioral Design Patterns — Part 1
When implementing a vending machine with the State pattern, how should the transition from 'WaitingForSelection' to 'Dispensing' state be handled after a user selects a product?
AThe 'WaitingForSelection' state calls <code>context.setState(new DispensingState())</code> within its handle method.
BThe Context class directly changes state without notifying the current state.
CThe 'Dispensing' state polls the Context to detect selection changes.
DThe transition is handled by an external controller, not by states.
Step-by-Step Solution
Solution:
  1. Step 1: Understand State pattern transitions

    State objects themselves manage transitions by updating the Context's state.
  2. Step 2: Analyze transition from 'WaitingForSelection' to 'Dispensing'

    The current state should invoke context.setState(new DispensingState()) when appropriate.
  3. Final Answer:

    The 'WaitingForSelection' state calls context.setState(new DispensingState()) within its handle method. -> Option A
  4. Quick Check:

    States control transitions by updating Context's state [OK]
Quick Trick: States themselves trigger transitions via context.setState() [OK]
Common Mistakes:
MISTAKES
  • Letting Context change state without state involvement
  • Using polling instead of event-driven transitions
  • Delegating transitions to external controllers

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More LLD Quizzes