Created
August 2, 2016 19:11
-
-
Save stepanhruda/77c62dfdeb821f597f7ccf14f1042be3 to your computer and use it in GitHub Desktop.
Turnstyle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct BrokenTurnstyle { | |
private let previousState: WorkingTurnstyle | |
func machineRepairDidComplete() -> WorkingTurnstyle { | |
return previousState | |
} | |
} | |
struct WorkingTurnstyle { | |
private(set) var state: State = .Locked(credit: 0) | |
private static let farePrice: UInt = 50 | |
enum State { | |
case Locked(credit: UInt) | |
case Unlocked | |
} | |
enum Command { | |
case SoundAlarm | |
case CloseDoors | |
case OpenDoors | |
} | |
mutating func insertCoin(value: UInt) -> Command? { | |
switch state { | |
case .Locked(let credit): | |
let newCredit = credit + value | |
if newCredit >= WorkingTurnstyle.farePrice { | |
state = .Unlocked | |
return .OpenDoors | |
} else { | |
return nil | |
} | |
case .Unlocked: | |
return nil | |
} | |
} | |
mutating func admitPerson() -> Command? { | |
switch state { | |
case .Unlocked: | |
state = .Locked(credit: 0) | |
return .CloseDoors | |
case .Locked: | |
return .SoundAlarm | |
} | |
} | |
func machineDidFail() -> BrokenTurnstyle { | |
return BrokenTurnstyle(previousState: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment