首页 > 解决方案 > 如何简化巨大的 switch-case 表达式?

问题描述

下一个代码我遇到了一些麻烦。我有简单的界面,如:

public interface Game {
    int start();
}

许多实现此接口的类如:

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

GameManager 类具有这样的一种方法:

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;
}

我试图使用这样的反射来简化这个 switch-case 构造:注解:

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

long value() default 0;
}

FirstGame类:

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

GameManager 方法是这样的:

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;
}

但它工作得太慢了。那么,如何以其他方式简化 switch-case 表达式呢?感谢和抱歉英语不好。

标签: javaperformanceoptimizationreflection

解决方案


这个怎么样?

static final List<Supplier<Game>> GAMES = List.of(
    FirstGame::new,
    SecondGame::new
    // ...
);

public Game getGameById(int id) {
    return GAMES.get(id).get();
}

或者

static final Map<Integer, Supplier<Game>> GAMES = Map.of(
    1, FirstGame::new,
    2, SecondGame::new
);

public Game getGameById(int id) {
    return GAMES.get(id).get();
}

推荐阅读