**请注意:**我是一名Java开发人员,对Scala没有任何实际应用知识(遗憾的是)。我希望答案中提供的任何代码示例都使用Akka的Java API。
我尝试使用Akka FSM API来建模下面的超简单状态机。实际上,我的机器要复杂得多,但是这个问题的答案将允许我推断出我的实际FSM。
所以我有两个状态:Off
和On
。您可以通过调用SomeObject#powerOn(<someArguments>)
打开计算机的电源来从Off -> On
切换到On -> Off
。您可以通过调用SomeObject#powerOff(<someArguments>)
关闭计算机的电源来从On -> Off
切换到SomeObject#powerOff(<someArguments>)
。
我想知道我需要什么参与者和支持类来实现这个FSM。我 * 相信 * 代表FSM的参与者必须扩展AbstractFSM
。但是什么类代表这两种状态?什么代码公开和实现powerOn(...)
和powerOff(...)
状态转换?一个工作的Java示例,甚至仅仅是Java伪代码,在这里对我来说都有很大帮助。
3条答案
按热度按时间xt0899hw1#
我认为我们可以做得比来自FSM docs(http://doc.akka.io/docs/akka/snapshot/java/lambda-fsm.html)的copypasta更好一些。
您有两个触发器(或事件,或信号)-- powerOn和powerOff。您希望将这些信号发送给一个Actor并使其改变状态,其中两个有意义的状态是On和Off。
现在,严格地说,FSM还需要一个组件:您希望在过渡时采取的操作。
你不需要一个动作,但是一个Actor不能被直接检查,也不能被直接修改。所有的变异和确认都是通过异步消息传递发生的。
在你的例子中,转换时没有提供任何操作,你的状态机基本上是无操作的。操作发生,状态转换没有副作用,状态是不可见的,所以一个工作的机器和一个坏的机器是一样的。由于这一切都是异步发生的,你甚至不知道坏的东西什么时候完成。
因此,请允许我稍微扩展一下您的合同,并在FSM定义中包括以下操作:
现在,我们也许能够构建一个实际上可测试的FSM。
让我们为您的两个信号定义一对类。(AbstractFSM DSL期望在类上匹配):
让我们为您的两个状态定义一对枚举:
让我们定义一个AbstractFSM Actor(http://doc.akka.io/japi/akka/2.3.8/akka/actor/AbstractFSM.html)。通过扩展AbstractFSM,我们可以使用与上面类似的FSM定义链来定义一个Actor,而不是直接在onReceive()方法中定义消息行为。它为这些定义提供了一个很好的DSL,并且(有点奇怪的是)期望在静态初始化器中设置这些定义。
不过,我们还是要绕个圈子:AbstractFSM定义了两个泛型,用于提供编译时类型检查。
S是我们希望使用的State类型的基,D是Data类型的基。(可能是电灯开关的功率表?),您将构建一个单独的类来保存这些数据,而不是尝试向AbstractFSM的子类添加新成员。由于我们没有数据,让我们定义一个伪类,这样您就可以看到它是如何传递的:
这样,我们就可以创建演员类了。
我肯定你在想:我该如何使用它呢?!让我们使用直接的JUnit和Akka Testkit for java来创建一个测试工具:
这就是你:一个FSM lightswitch。不过老实说,这样一个小例子并不能真正展示FSM的强大功能,因为一个无数据的例子可以作为一组“变成/不变成”行为来执行,所用的LoC只有一半,没有泛型或lambda。IMO的可读性更强。
PS考虑学习Scala,如果仅仅是为了能够阅读其他人的代码的话!Atomic Scala这本书的前半部分可以在网上免费获得。
PPS如果你真的想要一个可组合的状态机,我维护Pulleys,一个基于纯java的状态图的状态机引擎。它已经发展了很多年了(大量的XML和旧模式,没有DI集成),但是如果你真的想把状态机的实现从输入和输出中分离出来,可能会有一些灵感。
u59ebvdq2#
我知道Scala的演员。
此Java起始代码可以帮助您继续:
是的,从
AbstractFSM
扩展您的SimpleFSM
。州是
AbstractFSM
中的enum
。您的
<someArguments>
可以是您的AbstractFSM
中的Data
部件您的
powerOn
和powerOff
是参与者消息/事件。状态切换在转换部分真实的工作项目见
Scala and Java 8 with Lambda Template for a Akka AbstractFSM
hpxqektj3#
这是一个非常古老的问题,但如果你从Google获得了一个热门,但如果你仍然有兴趣用Akka实现FSM,我建议看看documentation的这一部分。
如果你想看看一个实用的模型驱动状态机是如何实现的,你可以查看我的blog1,blog2。