mercredi 19 août 2015

Initiate a subclass object from a string

Consider a multiplayer fighting game, where the client selects a fighter by sending to the server a string that contains the name of the fighter the client just selected.

Consider this "fighters" class structure in the server:

Fighter
   Foo extends Fighter
   Bar extends Fighter
   Qux extends Fighter

For instance the client sent this "Bar" string, how can I initiate a subclass according to this string?

The way I did it is an enum like so:

public enum Champion {
    Foo {
        @Override
        public Fighter getNew() {
            return new Foo();
        }
    },

    Bar {
        @Override
        public Fighter getNew() {
            return new Bar();
        }
    },

    Qux {
        @Override
        public Fighter getNew() {
            return new Qux();
        }
    };

    public abstract Fighter getNew();

    public static boolean contains(String fighter) {
        for (Champion c : Champion.values()) {
            if (c.name().equals(fighter)) {
                return true;
            }   
        }
        return false;
    }
}

Then I am getting an object like so:

public Fighter getFighter(String fighterName) {
    if(Champion.contains(fighterName)) {
        return Champion.valueOf(fighterName).getNew();
    } else { 
       return null; 
    } // For example sake only :)
}

Is this the correct way to deal with this encounter? is there a better way? I remember there is a known pattern to deal with such encounters, but cannot remember exactly which.
If you have an idea please let me know!

Aucun commentaire:

Enregistrer un commentaire