Explaining State Design Pattern
The state design pattern is a software design pattern in which an object's behavior is determined by its current state. This pattern is used to create objects that have a defined set of states and transitions between those states. In this pattern, the object's behavior changes depending on its current state, and it can change its state by executing certain operations.
Here is an example of the state design pattern in Swift:
protocol State {
func handleInput(_ input: String) -> State
func getDescription() -> String
}
class StartState: State {
func handleInput(_ input: String) -> State {
if input == "start" {
return RunningState()
} else {
return self
}
}
func getDescription() -> String {
return "Start state"
}
}
class RunningState: State {
func handleInput(_ input: String) -> State {
if input == "stop" {
return StoppedState()
} else {
return self
}
}
func getDescription() -> String {
return "Running state"
}
}
class StoppedState: State {
func handleInput(_ input: String) -> State {
return self
}
func getDescription() -> String {
return "Stopped state"
}
}
class ObjectWithState {
private var state: State
init() {
self.state = StartState()
}
func handleInput(_ input: String) {
state = state.handleInput(input)
}
func getDescription() -> String {
return state.getDescription()
}
}
let objectWithState = ObjectWithState()
print(objectWithState.getDescription()) // Start state
objectWithState.handleInput("start")
print(objectWithState.getDescription()) // Running state
objectWithState.handleInput("stop")
print(objectWithState.getDescription()) // Stopped state
In this example, the ObjectWithState
class has a state
property that determines its current behavior. This state
property is an instance of a type that conforms to the State
protocol. The ObjectWithState
class has a handleInput(_:)
method that changes its state based on the input it receives, and a getDescription()
method that returns a description of its current state.
The StartState
, RunningState
, and StoppedState
classes all conform to the State
protocol and define the behavior of the ObjectWithState
class in each of its possible states. When the ObjectWithState
instance receives the input "start"
, it transitions from the StartState
to the RunningState
, and when it receives the input "stop"
, it transitions from the RunningState
to the StoppedState
.