Facebook Pixel

Exercise: State

This exercise puts the State pattern lesson into code.

Scenario

Model a subway turnstile as a State machine. The turnstile starts in the Locked state and accepts two events: coin and push. Each event is processed by the current state object, which returns the output message and the next state. The Turnstile context delegates each event to its current state and swaps in whatever state the handler returns.

Commands

Each input row contains exactly one command string. Produce one output line per command.

Current stateEventOutputNext state
LockedcoinUnlockedUnlocked
LockedpushLocked: pay firstLocked
UnlockedcoinAlready unlockedUnlocked
UnlockedpushWalked throughLocked
Example
Input
7
coin
push
push
coin
coin
push
push
Output
Unlocked
Walked through
Locked: pay first
Unlocked
Already unlocked
Walked through
Locked: pay first
Explanation
The turnstile starts Locked. A `coin` unlocks it and outputs `Unlocked`. A `push` walks through and returns to Locked, outputting `Walked through`. A `push` while Locked outputs `Locked: pay first` and stays Locked. Another `coin` unlocks it again. A second `coin` while already unlocked outputs `Already unlocked` and stays Unlocked. Then `push` walks through (back to Locked), and a final `push` while Locked outputs `Locked: pay first`.

Your task

Create LockedState and UnlockedState (each implements TurnstileState) so the commands produce the output described above. The starter keeps TurnstileState and the Turnstile context, and marks where to add the two state classes with a TODO comment listing each method's signature and exact return value.

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro