有限状态机:是一种用来进行对象行为建模的工具,其做用主要是描述对象在它的生命周期内所经历的状态序列,以及如何响应来自外界的各类事件。在计算机科学中,有限状态机被普遍用于建模应用行为、硬件电路系统设计、软件工程,编译器、网络协议、和计算与语言的研究java
本文主要学习java的一个开源实现 squirrel-foundation 状态机git
1 |
现态、条件、动做、次态。“现态”和“条件”是因,“动做”和“次态”是果 |
通常来讲,随着项目的发展,代码变得愈来愈复杂,状态之间的关系,转化变得愈来愈复杂,好比订单系统状态,活动系统状态等。产品或者开发很难有一我的可以梳理清楚整个状态的全局. 使用状态机来管理对象生命周期能够使得代码具备更好的可读性,可维护性,以及可测试性。github
1 |
有限状态机是一种对象行为建模工具,适用对象有一个明确而且复杂的生命流(通常而言三个以上状态),而且在状态变迁存在不一样的触发条件以及处理行为。 |
先来看squirrel-foundation github 上面给出的例子,对状态机有一个直观的认识网络
添加maven 依赖maven
1 2 3 4 5 6 |
<!-- 状态机--> <dependency> <groupId>org.squirrelframework</groupId> <artifactId>squirrel-foundation</artifactId> <version>0.3.8</version> </dependency> |
QuickStartSample demo工具
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory; import org.squirrelframework.foundation.fsm.UntypedStateMachine; import org.squirrelframework.foundation.fsm.UntypedStateMachineBuilder; import org.squirrelframework.foundation.fsm.annotation.StateMachineParameters; import org.squirrelframework.foundation.fsm.impl.AbstractUntypedStateMachine; /** * @Author wtx * @Date 2019/5/5 */ public class QuickStartSample { // 1. Define State Machine Event enum FSMEvent { ToA, ToB, ToC, ToD } // 2. Define State Machine Class @StateMachineParameters(stateType=String.class, eventType=FSMEvent.class, contextType=Integer.class) static class StateMachineSample extends AbstractUntypedStateMachine { protected void fromAToB(String from, String to, FSMEvent event, Integer context) { System.out.println("Transition from '"+from+"' to '"+to+"' on event '"+event+ "' with context '"+context+"'."); } protected void ontoB(String from, String to, FSMEvent event, Integer context) { System.out.println("Entry State \'"+to+"\'."); } } public static void main(String[] args) { // 3. Build State Transitions UntypedStateMachineBuilder builder = StateMachineBuilderFactory.create(StateMachineSample.class); builder.externalTransition().from("A").to("B").on(FSMEvent.ToB).callMethod("fromAToB"); builder.onEntry("B").callMethod("ontoB"); // 4. Use State Machine UntypedStateMachine fsm = builder.newStateMachine("A"); fsm.fire(FSMEvent.ToB, 10); System.out.println("Current state is "+fsm.getCurre5ntState()); } } |
首先使用StateMachineBuilderFactory构造一个UntypedStateMachineBuilder,而后builder.externalTransition(),builder除了externalTransition还有internalTransition(),学习
.from(“A”).to(“B”).on(FSMEvent.ToB).callMethod(“fromAToB”);
当状态在A 发生 ToB 事件时,调用 方法fromAToB,而后状态转化到 B。
builder.onEntry(“B”).callMethod(“ontoB”);
当状态转移到B 时,调用方法ontoB。测试
1 2 3 |
UntypedStateMachine fsm = builder.newStateMachine("A"); // 触发ToB事件 fsm.fire(FSMEvent.ToB, 10); |
1 |
fsm.getCurrentState() |