java - 如何简化巨大的 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 表达式呢?感谢和抱歉英语不好。
解决方案
这个怎么样?
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();
}
推荐阅读
- npm - Should I duplicate "peerDependencies" in "dependencies" field of "package.json"?
- docker - 从 traefik 到 Vultr 的 DNS 挑战
- javascript - 两个按钮中的一个启动滚动,但它们都应该
- c - 如何在 C 运行时获取哪些有问题的源代码和行?
- oracle - 在Oracle中查找某个时期内帐户总和之间的差异
- linux - ubuntu 中的 systemd 文件未按预期运行
- stata - Stata中看似无关的回归后的利润率太慢
- css - JavaFX TabPane:如何制作梯形标签
- javascript - Firebase Firestore - 如何查询两个匹配的“WHERE”子句中的任何一个
- python - 带有循环的 Python 列表 remove() 无法按预期工作