Created
January 1, 2019 15:16
-
-
Save LH17/39889d3794153370468670e39d931b5d to your computer and use it in GitHub Desktop.
State Design Pattern
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
protocol Human { | |
// MARK: - Getter | |
func getState() -> ManState | |
// MARK: - Setter | |
func set(state: ManState) | |
} | |
protocol ManState { | |
func stand() | |
func walk() | |
func run() | |
func toString() -> String | |
} | |
extension ManState { | |
func stand() {} | |
func walk() {} | |
func run() {} | |
} | |
class Man: Human { | |
var state: ManState? | |
init() { | |
state = nil | |
} | |
func set(state: ManState) { | |
self.state = state | |
} | |
func getState() -> ManState { | |
return state! | |
} | |
} | |
class StandingState: ManState { | |
var human: Human | |
init(_ human: Human) { | |
self.human = human | |
} | |
func stand() { | |
print("The man is in standing position") | |
human.set(state: self) | |
} | |
func toString() -> String { | |
return "Standing State" | |
} | |
} | |
class WalkingState: ManState { | |
var human: Human | |
init(_ human: Human) { | |
self.human = human | |
} | |
func walk() { | |
print("The man is in walking position") | |
human.set(state: self) | |
} | |
func toString() -> String { | |
return "Walking State" | |
} | |
} | |
class RunningState: ManState { | |
var human: Human | |
init(_ human: Human) { | |
self.human = human | |
} | |
func run() { | |
print("The man is in running position") | |
human.set(state: self) | |
} | |
func toString() -> String { | |
return "Running State" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment