将类存储在映射中,并在查找类后创建对象



我有三个类似的类,我想用一个变量实例化其中一个。基本上转换为:

Cell cell;
switch("CellA") {
case "cellA":
cell = new CellA(); break;
case "cellB":
cell = new CellB(); break;
case "cellC":
cell = new CellC(); break;
}

像这样的

Cell cell;
//Using a map
Map<String, Type> map = new HashMap<String, Type>();
map.put("cellA", CellA);  
map.put("cellB", CellB);
map.put("cellC", CellC);  //CellA, CellB, CellC are the class types
Type cellType = map.get("cellA");
cell = new cellType.getClass();   //This is problematic, I hope cellType is an alias to a cell class, so I can use keyword "new"

(注:CellA、CellB、CellC扩展Cell类(

我知道这样做听起来有点奇怪,但我的教授真的希望我们避免切换语句。(这是一个软件设计类(

如果您使用Java 8+,您可以使用供应商实现动态工厂:

public class DynamicFactory {
private static final Map<String, Supplier<? extends Cell>> registry = new HashMap<>();
public void register(String type, Supplier<? extends Cell> supplier) {
registry.putIfAbsent(type, supplier);
}
public Cell getCell(String type) {
return Optional.ofNullable(registry.get(type))
.map(Supplier::get)
.orElse(null);
}
public static void main(String[] args) {
DynamicFactory app = new DynamicFactory();
app.register("cellA", CellA::new);
app.register("cellB", CellB::new);
app.register("cellC", CellC::new);
System.out.println(app.getCell("cellA"));  // CellA@8bcc55f
System.out.println(app.getCell("cellB"));  // CellB@14dad5dc
System.out.println(app.getCell("cellC"));  // CellC@764c12b6
System.out.println(app.getCell("cellD"));  // null
}
}