Last active
July 31, 2022 06:52
-
-
Save motorro/88c3b397a906de752abb7394256ed713 to your computer and use it in GitHub Desktop.
State machine implementation
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
/** | |
* Common state machine | |
* @param G UI gesture | |
* @param U UI state | |
*/ | |
interface CommonStateMachine<G: Any, U: Any> : MachineInput<G>, MachineOutput<G, U> { | |
/** | |
* Base state-machine implementation | |
* @param init Initial state producer | |
*/ | |
abstract class Base<G: Any, U: Any>( | |
private val init: () -> CommonMachineState<G, U> | |
) : CommonStateMachine<G, U> { | |
/** | |
* Active machine state | |
*/ | |
protected lateinit var activeState: CommonMachineState<G, U> | |
/** | |
* Sets active machine state | |
*/ | |
final override fun setMachineState(machineState: CommonMachineState<G, U>) { | |
clear() | |
activeState = machineState | |
startMachineState() | |
} | |
/** | |
* Starts machine | |
*/ | |
protected fun start() { | |
activeState = init() | |
startMachineState() | |
started = true | |
} | |
/** | |
* Updates state with UI gesture | |
* @param gesture UI gesture to proceed | |
*/ | |
final override fun process(gesture: G) { | |
activeState.process(gesture) | |
} | |
/** | |
* Cleans-up state-machine | |
*/ | |
final override fun clear() { | |
activeState.clear() | |
} | |
/** | |
* Starts machine state | |
*/ | |
private fun startMachineState() { | |
activeState.start(this) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment