博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用enum建立简单的状态机
阅读量:6449 次
发布时间:2019-06-23

本文共 2988 字,大约阅读时间需要 9 分钟。

Overview

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.

Enum for Singleton and Utility class

You can use an enum as a Singleton or Utility very simply.

enum Singleton {    INSTANCE;}enum Utility {    ; // no instances}

Enum to implement an interface

You can also implement an interface in an enum.

interface Named {    public String name();    public int order();}enum Planets implements Named {    Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune;    // name() is implemented automagically.    public int order() { return ordinal()+1; }}

Each Enum Instance a different sub-class

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

// from http://download.oracle.com/javase/1,5.0/docs/guide/language/enums.htmlpublic enum Operation {  PLUS   { double eval(double x, double y) { return x + y; } },  MINUS  { double eval(double x, double y) { return x - y; } },  TIMES  { double eval(double x, double y) { return x * y; } },  DIVIDE { double eval(double x, double y) { return x / y; } };  // Do arithmetic op represented by this constant  abstract double eval(double x, double y);}

Using an enum as a state machine

What you can do with all these techniques is to create a enum based statement.
091312189651022.jpg

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.

interface Context {    ByteBuffer buffer();    State state();    void state(State state);}interface State {    /**       * @return true to keep processing, false to read more data.     */    boolean process(Context context);}enum States implements State {    XML {        public boolean process(Context context) {            if (context.buffer().remaining() < 16) return false;            // read header            if(headerComplete)                context.state(States.ROOT);            return true;        }    }, ROOT {        public boolean process(Context context) {            if (context.buffer().remaining() < 8) return false;            // read root tag            if(rootComplete)                context.state(States.IN_ROOT);            return true;        }    }}public void process(Context context) {    socket.read(context.buffer());    while(context.state().process(context));}

写在后面

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

参考资料

  • 有限状态机()
  • 自动机编程()
==============================================================================
本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/p/3962475.html,如需转载请自行联系原作者
你可能感兴趣的文章
js 深拷贝,浅拷贝
查看>>
LeetCode刷题: 整数反转
查看>>
#学习笔记# 记录一次java父类转子类的方法
查看>>
Vue源码分析系列四:Virtual DOM
查看>>
Git 版本回退
查看>>
Python:使用pypdf2合并、分割、加密pdf文件。
查看>>
rabbitmq java 应用实例
查看>>
Flutter Mac下环境配置
查看>>
springCloud学习1(集中式配置管理)
查看>>
React-Amap-HOC组件封装
查看>>
我的友情链接
查看>>
node.js操作MySQL数据库
查看>>
oracle常用字段类型
查看>>
mapreduce/spark/storm/Tez 框架
查看>>
20个简化开发任务的JavaScript库
查看>>
Junit 小案列 基本注解
查看>>
微信小程序 - 选择图片、预览图片、删除图片
查看>>
软件开发sql优化建议
查看>>
web前端工作者需要具备的技能
查看>>
C语言和C++标准输入
查看>>