如何在干净的架构中实现状态机?

问题描述 投票:0回答:1

假设状态机有一个状态列表:

seald class State {
   data class A : State()
   data class B : State()
   data class C : State()
   data class D : State()
}

所以根据干净的架构,状态是域模型。但是工具是否在这些状态之间切换?

StateMachineManager
该放在哪里?或者如何在用例之间分割它?

android kotlin state-machine clean-architecture
1个回答
0
投票

选项 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
}
© www.soinside.com 2019 - 2024. All rights reserved.