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?