您所做的可能是最好的方法,直到可以使用字符串开关为止。 (2019年编辑:可以使用字符串开关 - 使用它。)
您可以创建工厂对象以及从字符串到这些对象的映射。但在当前的 Java 中,这确实有点冗长。
private interface AnimalFactory {
Animal create();
}
private static final Map<String,AnimalFactory> factoryMap =
Collections.unmodifiableMap(new HashMap<String,AnimalFactory>() {{
put("Meow", new AnimalFactory() { public Animal create() { return new Cat(); }});
put("Woof", new AnimalFactory() { public Animal create() { return new Dog(); }});
}});
public Animal createAnimal(String action) {
AnimalFactory factory = factoryMap.get(action);
if (factory == null) {
throw new EhException();
}
return factory.create();
}
在最初编写此答案时,针对 JDK7 的功能可能会使代码如下所示。事实证明,lambda 出现在 Java SE 8 中,并且据我所知,还没有映射文字的计划。 (2016年编辑)
private interface AnimalFactory {
Animal create();
}
private static final Map<String,AnimalFactory> factoryMap = {
"Meow" : { -> new Cat() },
"Woof" : { -> new Dog() },
};
public Animal createAnimal(String action) {
AnimalFactory factory = factoryMap.get(action);
if (factory == null) {
throw EhException();
}
return factory.create();
}
2019年编辑:目前,这看起来像这样。
import java.util.function.*;
import static java.util.Map.entry;
private static final Map<String,Supplier<Animal>> factoryMap = Map.of(
"Meow", Cat::new, // Alternatively: () -> new Cat()
"Woof", Dog::new // Note: No extra comma like arrays.
);
// For more than 10, use Map.ofEntries and Map.entry.
private static final Map<String,Supplier<Animal>> factoryMap2 = Map.ofEntries(
entry("Meow", Cat::new),
...
entry("Woof", Dog::new) // Note: No extra comma.
);
public Animal createAnimal(String action) {
Supplier<Animal> factory = factoryMap.get(action);
if (factory == null) {
throw EhException();
}
return factory.get();
}
如果要添加参数,则需要切换Supplier
to Factory
(and get
变成apply
这在上下文中也没有意义)。对于两个参数BiFunction
。超过两个参数,您将再次尝试使其可读。