Implementing communication protocol in Java using state pattern design

后端 未结 2 819
别跟我提以往
别跟我提以往 2021-02-11 04:20

Apologies if this is answered elsewhere; couldn\'t find enough information to convince myself of the best way to do this. I also realize this is a lengthy explanation with no co

2条回答
  •  逝去的感伤
    2021-02-11 04:24

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

提交回复
热议问题