### 1、添加依赖

新建一个 java maven 项目，并添加依赖

```xml
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon-statemachine</artifactId>
</dependency>
```


### 2、添加一个 DemoApp 类

复制，即可运行


```java
import org.noear.solon.statemachine.EventContext;
import org.noear.solon.statemachine.StateMachine;

public class DemoApp {
    //定义事件（一个事件：按下按钮）
    enum Event {PRESS}
    
    //定义状态（关闭，开启）
    enum State {OFF,ON}
    
    public static void main(String[] args) {
        // 1. 创建状态机
        StateMachine<State, Event, String> stateMachine = new StateMachine<>();

        // 2. 配置转换规则：OFF -> ON
        stateMachine.addTransition(t -> t.from(State.OFF).on(Event.PRESS).to(State.ON)
                .then(context -> {
                    System.out.println("你好，💡 灯亮了！");
                })
        );

        // 3. 配置规则：ON -> OFF
        stateMachine.addTransition(t -> t.from(State.ON).on(Event.PRESS).to(State.OFF)
                .then(context -> {
                    System.out.println("你好，🌙 灯灭了！");
                })
        );

        // 4. 状态机测试
        State currentState = State.OFF;
        for (int i = 0; i < 10; i++) {
            currentState = stateMachine.sendEvent(Event.PRESS, EventContext.of(currentState, null));
            System.out.println("新状态: " + currentState);
        }
    }
}
```


### 3、运行效果

<img src="/img/373db4706251418c9309d2753bbcf5d8.png" width="500" />
