假设状态机有一个状态列表:
seald class State {
data class A : State()
data class B : State()
data class C : State()
data class D : State()
}
所以根据干净的架构,状态是域模型。但是工具是否在这些状态之间切换?
StateMachineManager
该放在哪里?或者如何在用例之间分割它?
选项 1:集中式状态机管理器
sealed class State {
data class A : State()
data class B : State()
data class C : State()
data class D : State()
}
class StateMachineManager {
private var currentState: State = State.A()
fun transition(event: Event): State {
currentState = when (currentState) {
is State.A -> handleStateA(event)
is State.B -> handleStateB(event)
// ... other states
}
return currentState
}
private fun handleStateA(event: Event): State {
}
private fun handleStateB(event: Event): State {
}
// ... other state handlers
}
选项 2:每个转换都有单独的用例
class TransitionFromAToBUseCase {
fun execute(currentState: State.A, event: Event): State {
}
}
class TransitionFromBToCUseCase {
fun execute(currentState: State.B, event: Event): State {
}
// ... other use cases
}
用例层中的集中式状态机管理器:
class StateMachineManager {
private var currentState: State = State.A()
fun processEvent(event: Event): State {
currentState = when (currentState) {
is State.A -> processEventInStateA(event)
is State.B -> processEventInStateB(event)
// ... other states
}
return currentState
}
private fun processEventInStateA(event: Event): State {
return when (event) {
is Event.SomeEvent -> State.B()
else -> currentState
}
}
private fun processEventInStateB(event: Event): State {
return when (event) {
is Event.AnotherEvent -> State.C()
else -> currentState
}
}
// ... other state-specific methods
}