天天看点

使用enum建立简单的状态机

the enum in java is more powerful than many other languages which can lead to surprising uses.

in this article, i outline some the individual features of enum in java, and put them together to form a state machine.

you can use an enum as a singleton or utility very simply.

you can also implement an interface in an enum.

you can override the behaviour of an instance. this effectively give the instance a different sub-class of the enum with its own implementation.

using an enum as a state machine

what you can do with all these techniques is to create a enum based statement.

使用enum建立简单的状态机

in this short example, a parser state machine processes raw xml from a bytebuffer. each state has its own process method and if there is not enough data available, the state machine can return to retrieve more data. each transition between states is well defined and the code for all states is together in one enum.

个人感觉使用如果想真的实现一个完整的finite-state machine的话,上面的例子真的是太基础了。不过参考上面的用法可以帮助我们减少很多的if else if等代码。另外涉及到“分支处理”的情况,在实际的工作中,我更多的还是会选择“策略模式”。