Tre*_*vor 34 java enums state-machine fsm
我在Android应用程序中使用了几个基于枚举的状态机.虽然这些工作非常好,但我正在寻找的是如何优雅地接收事件,通常是从已注册的回调或从事件总线消息接收到当前活动状态的建议.在有关基于枚举的FSM的许多博客和教程中,大多数都提供了使用数据的状态机(例如解析器)的示例,而不是展示如何从事件驱动这些FSM.
我正在使用的典型状态机具有以下形式:
private State mState;
public enum State {
SOME_STATE {
init() {
...
}
process() {
...
}
},
ANOTHER_STATE {
init() {
...
}
process() {
...
}
}
}
...
Run Code Online (Sandbox Code Playgroud)
在我的情况下,一些状态会触发一项特定对象的工作,注册一个监听器.该工作完成后,该对象将异步回调.换句话说,只是一个简单的回调接口.
同样,我有一个EventBus.希望再次通知事件的类实现回调接口以及listen()EventBus上的那些事件类型.
因此,基本问题是状态机或其各个状态,或包含枚举FSM的类,或某些东西必须实现这些回调接口,以便它们可以表示当前状态的事件.
我使用的一种方法是整个enum实现回调接口.枚举本身在底部具有回调方法的默认实现,然后各个状态可以覆盖他们感兴趣的事件的回调方法.为此,每个状态必须在进入和退出时注册和取消注册,否则在不是当前状态的状态下发生回调的风险.如果我找不到更好的东西,我可能会坚持这一点.
另一种方法是包含类来实现回调.然后,它必须通过调用将这些事件委托给状态机mState.process( event ).这意味着我需要枚举事件类型.例如:
enum Events {
SOMETHING_HAPPENED,
...
}
...
onSometingHappened() {
mState.process( SOMETHING_HAPPENED );
}
Run Code Online (Sandbox Code Playgroud)
我不喜欢这样,因为(a)我需要对每个状态中switch的事件类型进行丑陋,并且process(event)(b)传递其他参数看起来很尴尬.
我想建议一个优雅的解决方案,而不需要使用库.
Dim*_*ima 23
为什么没有事件直接在状态上调用正确的回调?
public enum State {
abstract State processFoo();
abstract State processBar();
State processBat() { return this; } // A default implementation, so that states that do not use this event do not have to implement it anyway.
...
State1 {
State processFoo() { return State2; }
...
},
State2 {
State processFoo() { return State1; }
...
}
}
public enum Event {
abstract State dispatch(State state);
Foo {
State dispatch(State s) { return s.processFoo(); }
},
Bar {
State dispatch(State s) { return s.processBar(); }
}
...
}
Run Code Online (Sandbox Code Playgroud)
这解决了原始方法的两种保留:没有"丑陋"的开关,也没有"尴尬"的附加参数.
mer*_*ike 16
因此,您希望将事件分派给其处理程序以获取当前状态.
要调度到当前状态,在每个状态变为活动状态时进行预订,并在其变为非活动状态时取消订阅是相当麻烦的.订阅知道活动状态的对象更容易,并且只是将所有事件委托给活动状态.
要区分事件,您可以使用单独的事件对象,然后使用访问者模式区分它们,但这是相当多的样板代码.我只会这样做,如果我有其他代码将所有事件都视为相同(例如,如果事件必须在交付之前缓冲).否则,我会做一些类似的事情
interface StateEventListener {
void onEventX();
void onEventY(int x, int y);
void onEventZ(String s);
}
enum State implements StateEventListener {
initialState {
@Override public void onEventX() {
// do whatever
}
// same for other events
},
// same for other states
}
class StateMachine implements StateEventListener {
State currentState;
@Override public void onEventX() {
currentState.onEventX();
}
@Override public void onEventY(int x, int y) {
currentState.onEventY(x, y);
}
@Override public void onEventZ(String s) {
currentState.onEventZ(s);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑
如果您有许多事件类型,最好使用字节码工程库或甚至普通的JDK代理在运行时生成无聊的委托代码:
class StateMachine2 {
State currentState;
final StateEventListener stateEventPublisher = buildStateEventForwarder();
StateEventListener buildStateEventForwarder() {
Class<?>[] interfaces = {StateEventListener.class};
return (StateEventListener) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
return method.invoke(currentState, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这使代码的可读性降低,但无需为每种事件类型编写委托代码.
您处于良好的轨道上,您应该使用与您的状态机结合的策略模式.在状态枚举中实现事件处理,提供默认的通用实现,并可能添加特定的实现.
定义您的事件和相关的策略界面:
enum Event
{
EVENT_X,
EVENT_Y,
EVENT_Z;
// Other events...
}
interface EventStrategy
{
public void onEventX();
public void onEventY();
public void onEventZ();
// Other events...
}
Run Code Online (Sandbox Code Playgroud)
然后,在你的State枚举中:
enum State implements EventStrategy
{
STATE_A
{
@Override
public void onEventX()
{
System.out.println("[STATE_A] Specific implementation for event X");
}
},
STATE_B
{
@Override
public void onEventY()
{
System.out.println("[STATE_B] Default implementation for event Y");
}
public void onEventZ()
{
System.out.println("[STATE_B] Default implementation for event Z");
}
};
// Other states...
public void process(Event e)
{
try
{
// Google Guava is used here
Method listener = this.getClass().getMethod("on" + CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, e.name()));
listener.invoke(this);
}
catch (Exception ex)
{
// Missing event handling or something went wrong
throw new IllegalArgumentException("The event " + e.name() + " is not handled in the state machine", ex);
}
}
// Default implementations
public void onEventX()
{
System.out.println("Default implementation for event X");
}
public void onEventY()
{
System.out.println("Default implementation for event Y");
}
public void onEventZ()
{
System.out.println("Default implementation for event Z");
}
}
Run Code Online (Sandbox Code Playgroud)
根据EventStrategy,所有事件都有默认实现.此外,对于每个状态,可以针对不同的事件处理进行特定实现.
该StateMachine会看起来像:
class StateMachine
{
// Active state
State mState;
// All the code about state change
public void onEvent(Event e)
{
mState.process(e);
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您信任mState是当前活动状态,所有事件仅应用于此状态.如果你想添加一个安全层,要禁用所有非活动状态的所有事件,你可以这样做,但在我看来,这不是一个好的模式,它不是一个State知道它是否活跃但它的StateMachine工作.
当你已经拥有一个事件总线时,我不清楚为什么你需要一个回调接口.总线应该能够根据事件类型向侦听器传递事件,而无需接口.考虑像Guava这样的架构(我知道你不想诉诸外部库,这是我想引起你注意的设计).
enum State {
S1 {
@Subscribe void on(EventX ex) { ... }
},
S2 {
@Subscribe void on(EventY ey) { ... }
}
}
// when a state becomes active
eventBus.register(currentState);
eventBus.unregister(previousState);
Run Code Online (Sandbox Code Playgroud)
我相信这种方法与你对梅里顿的答案的第一个评论一致:
不是手动编写类StateMachine来实现相同的接口并将事件转发到currentState,而是可以使用反射(或其他东西)自动化它.然后外部类将在运行时注册为这些类的侦听器并将它们委托给它,并在进入/退出时注册/取消注册状态.