Implementing communication protocol in Java using state pattern design

本小妞迷上赌 提交于 2019-12-03 08:58:12

I have used an enum for this style of parsing with one enum for each state. An example is here http://vanillajava.blogspot.co.uk/2011/06/java-secret-using-enum-as-state-machine.html

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));
}

I would first consider the following points :

  1. Are your state components (WAITING_FOR_COMMAND, COMMAND_RECEIVED etc )central to your application logic ? That is to say , does it really matter a lot what state the parser is in , and what state it transitions to , for the app to work correctly ? What are the values that each of the state is going to hold ? Do these values differ greatly from one state to another ? If your answers are yes , then probably you have a valid case for State pattern.But I have often seen state machines used in places where it was simply an overkill.

  2. Your use-case seems more like in need of Command pattern and an Interpreter pattern ( as it seems you are writing a grammar ).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!