CS FundamentalsHardProduct-company design interview

A vending machine's behaviour for insertCoin() and selectItem() differs completely in the states Idle, HasCoin, Dispensing and SoldOut, and the machine moves between these states itself. Which pattern models this, and how does it differ from Strategy?

  1. A. Strategy; the client swaps the algorithm, exactly as here
  2. B. State; the object switches its own state objects as events occur, while in Strategy the client usually picks the algorithm
  3. C. Template Method; each state overrides a step of the algorithm
  4. D. Command; each state is a request object

Correct answer: B. State; the object switches its own state objects as events occur, while in Strategy the client usually picks the algorithm

State and Strategy have the same class shape (delegation to an interchangeable object), but in State the transitions are driven internally by the context and the states often know about each other. Strategy is chosen from outside and the strategies are independent.

More Software Engineering, Git and Cloud Basics questions

Exams that ask this topic