mardi 7 juillet 2015

Instantiate class dynamically based on some constant in Java

I am making a multiplayer game which makes heavy use of a serialisable Event class to send messages over a network. I want to be able to reconstruct the appropriate subclass of Event based on a constant.

So far I have opted for the following solution:

public class EventFactory {

    public static Event getEvent(int eventId, ByteBuffer buf) {
        switch (eventId){
        case Event.ID_A:
            return EventA.deserialise(buf);
        case Event.ID_B:
            return EventB.deserialise(buf);
        case Event.ID_C:
            return EventC.deserialise(buf);
        default:
            // Unknown Event ID
            return null;
        }
    }

}

However, this strikes me as being very verbose and involves adding a new 'case' statement every time I create a new Event type.

I am aware of 2 other ways of accomplishing this, but neither seems better*:

  1. Create a mapping of constants -> Event subclasses, and use clazz.newInstance() to instantiate them (using an empty constructor), followed by clazz.initialiase(buf) to supply the necessary parameters.
  2. Create a mapping of constants -> Event subclasses, and use reflection to find and call the right method in the appropriate class.

Is there a better approach than the one I am using? Am I perhaps unwise to disregard the alternatives mentioned above?


*NOTE: in this case better means simpler / cleaner but without compromising too much on speed.





Aucun commentaire:

Enregistrer un commentaire