Akuna State Machine
The state machine is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number of states at any given time. This library helps you to implement the model.
Terminology
Stateful object - any entity which implements StatefulObject
interface and has finite numbers of states.
Source state - the state of an entity in the moment of starting transition process.
Target state - the desired state of an entity after finish of transition.
Event - any signal notifying about some event.
Transition - changing the entity's state from source to target according the incoming event.
State context - a context which contains all necessary information for the transition.
Action - the step of transition which performs some logic. If any action fails then the whole transition will be treated as failed.
Condition - a rule which determines possibility of transition at this moment. If any condition returns false then transition will not be performed.
Add dependency in your project
<dependency>
<groupId>com.github.kabal163</groupId>
<artifactId>state-machine</artifactId>
<version>0.4.1</version>
</dependency>
You need to implement LifecycleConfiguration
and configure your lifecycle.
The main class you interact with is LifecycleManager
. It responsible for applying appropriate transition to your entity according entities current state and incoming event.
You need to create it using its default implementation LifecycleManagerImpl
.
@Bean
public LifecycleManager<State, Event> myLifecycleManager(LifecycleConfiguration<State, Event> configuration) {
Map<String, Lifecycle<State, Event>> lifecyclesByName = new JavaConfigLifecyclesInitializer().initialize(singleton(configuration));
TransitionProvider<State, Event> transitionProvider = new TransitionProviderImpl<>(lifecyclesByName);
return new LifecycleManagerImpl<>(transitionProvider);
}
So, in order to create the LifecycleManager
you need to:
- Implement
LifecycleConfiguration
and describe your lifecycle - Use
JavaConfigLifecyclesInitializer
in order to createLifecycle
from theLifecycleConfiguration
- Create
TransitionProvider
and pass the created lifecycle to it. - Create the
LifecycleManager
and pass theTransitionProvider
to it.
That's all.
In order to perform a transition you need to use the execute
method of LifecycleManager
. It receives the stateful object, event and optionally a map of any variables which are needed during a transition. LifecycleManager
will put those variables to the state context. You can use the state context in your conditions and actions. Also, you can share some data between conditions and actions via the state context.
Example:
lifecycleManager.execute(myStatefulObject, MY_EVENT)
This method returns TransitionResult
which contains information about performed transition.