Advanced OOP and patterns · 14 / 15 Exercise Hard

States of an order

Objective

The State pattern represents each state as a class that knows which other states can be reached. That way the valid transitions are defined in one place, instead of being spread in conditions all over the program.

Instructions

  • An order starts as new. The actions are pay (new → paid), ship (paid → shipped), deliver (shipped → delivered) and cancel (from new or paid → cancelled).
  • The first line has the number n of actions; then one per line. Show State: new state if it is valid, or Invalid transition: action from state if it is not (the state does not change).
Input
3
pay
ship
deliver
Output
State: paid
State: shipped
State: delivered

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise