mercredi 20 juin 2018

Factory for client requests based on request identifier

In my program i'm getting requests from client via java socket. Each request have unique command identifier which corresponds to specified command on application side.

Now i have a class with very large switch in it, which creates instances of command classes depending on received command id. This class receives ByteBuffer with request data from client, and ClientConnection object(a class which represents connection between client and server). It reads ByteBuffer first two bytes, and gets corresponding command(instance of class that extends ClientRequest class) It looks like so:

public static ClientRequest handle(ByteBuffer data, ClientConnection client) {
    int id = data.getShort();  //here we getting command id
    switch (id) {
        case 1:
            return new CM_ACCOUNT_LOGIN(data, client, id);
        case 2:
            return new CM_ENTER_GAME(data, client, id);
        //...... a lot of other commands here
        case 1000:
            return new CM_EXIT_GAME(data, client, id);

    }
    //if command unknown - logging it
    logUnknownRequest(client, id);
    return null;
}

I don't like so large switch construction. My question is - is there some ways to refactor this code to make it more elegant? Maybe use some pattern?

Also, in future i want to try to use dependency injection(Guice) in my program, could it be used for instantinating ClientRequest instances depending on received id?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire