what are good design patterns to decide what method to call on a server based on the current connection state?

Let’s say a server receives messages, and based on the current state it has to decide what to do.

The obvious idea would be to use a enum:

enum State{LISTEN, SYN_REC, ESTABLISHED};
State state = State.LISTEN;

void msgReceived(Object msg){
if(state==State.LISTEN){ /* … */ }
     else if(state == State.SYN_REC){ /* … */ }
     else if(state == State.ESTABLISHED){ /* … */ }
}

This is very ugly code.

Next idea was to make the enum provide a handle-method:

enum State {
    LISTEN{ public void handle(Object msg){ /* … */ } },
    SYN_REC{ public void handle(Object msg){ /* … */ } },
    ESTABLISHED{ public void handle(Object msg){ /* … */ } };
    public abstract void handle(Object msg);
};

State state = State.LISTEN;

void msgReceived(Object msg){
    state.handle(msg);
}

looks much cleaner than the first idea, but is also problematic. The enum does not have access to attributes and methods defined on the server level. One would have to pass in all variables necessary for handle.

Is there any cleaner way to do this, I would like to avoid having to define additional public classes for this?

有帮助吗?

解决方案

This is definitely a Strategy pattern. The cool way you could implement this is by pairing it with the state pattern as enums.

So, your example is on the right track. Declare an abstract method in your enum then have every state implement it. With the return result being the new state.

And, yes, given you know so very little until call-time you would have to pass all this information in the call.

Example of abstract enums

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top