jeudi 27 août 2020

How to simplify huge switch-case expression?

I have got some troubles with next code. I have simple interface like:

public interface Game {
    int start();
}

Many classes that implements this interface like:

public class FirstGame implements Game {
    public static final int ID = 1;
    
    @Override
    int start() {
        // Do something and return result
    }
}

And GameManager class that has one method like this:

public Game getGameById(int id) {
    switch(id) {
        case FirstGame.ID:
            return new FirstGame();
        case SecondGame.ID:
            return new SecondGame();
        // ..... and many other cases....
    }
    return null;
}

I was trying to simplify this switch-case construction using reflection like this: Annotation:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface GameId {

long value() default 0;
}

FirstGame class:

@GameId(value = 1)
public class FirstGame implements Game {
    public static final int ID = 1;
    
    @Override
    int start() {
        // Do something and return result
    }
}

And GameManager method like this:

public Game getGameById(int id) {
    Game game = null;
    try {
        Reflections reflections = new Reflections();
        for (Class<?> clazz : reflections.getTypesAnnotatedWith(GameId.class)) {
            if (clazz.getAnnotation(GameId.class).value() == id) {
                Constructor constructor = clazz.getConstructor();
                game = (Game) constructor.newInstance();
                break;
            }
        }
    } catch (Exception ex) { ex.printStackTrace();}
    return game;
}

But it works too slow. So, how to simplify switch-case expression in some other way? Thanks and sorry for broken English.





Aucun commentaire:

Enregistrer un commentaire