面试题答案
一键面试设计思路
- 定义密封类:使用密封类来表示状态机的所有可能状态,这样可以在编译期确保状态的完整性,避免遗漏状态处理。
- 定义状态转换方法:在密封类中定义方法来处理状态转换逻辑,每个具体状态实现对应的转换逻辑。
- 处理逻辑:每个具体状态类实现状态对应的处理逻辑。
代码实现
sealed class State {
object Initial : State()
object Intermediate : State()
object Final : State()
// 状态转换方法,这里以从Initial转换到Intermediate为例
fun transition(): State {
return when (this) {
is Initial -> Intermediate
is Intermediate -> Final
is Final -> this
}
}
// 处理逻辑方法
fun handle() {
when (this) {
is Initial -> println("处理初始状态逻辑")
is Intermediate -> println("处理中间状态逻辑")
is Final -> println("处理最终状态逻辑")
}
}
}
使用示例
fun main() {
var currentState = State.Initial
currentState.handle()
currentState = currentState.transition()
currentState.handle()
currentState = currentState.transition()
currentState.handle()
}
上述代码中,首先定义了一个密封类 State
,包含 Initial
、Intermediate
和 Final
三个具体状态。transition
方法用于处理状态转换逻辑,handle
方法用于处理每个状态对应的业务逻辑。在 main
函数中演示了状态的转换和处理逻辑的执行。