切换对象创建重构

switch object creation refactor

假设我有 classes A,B 它们每个都扩展了一些 class X。 我想要一种基于某些参数值(值是其他逻辑的结果)创建 A 或 B 的方法。

我可以不使用 switch 语句吗?

即:

class X {...}
class A extends X {...}
class B extends X {...}

做一个 class:

太天真了
class Z {
    X createObject(int type) {
        switch(type)
            case 1: return new A();
            ...
            case 2: return new B();
}

是的,您可以在没有 switch 语句的情况下完成。我建议使用数组或 MapSupplier.

Map<Integer, Supplier<X>> map = new HashMap<>();
map.put(1, A::new); // () -> new A()
map.put(2, B::new); // () -> new B()

X createObject(int type) {
    Supplier<X> supplier = map.get(type);
    if (supplier == null) return null;
    return supplier.get();
}

您当然可以不使用 switch 语句。

如果只有少数情况,您可以使用三元运算符。

  public static X createObject(int type) {
    return type == 1 ?
      new A() :
      type == 2 ?
        new B() :
        null;
  }

您也可以使用更通用的方法:

  private static final Map<Integer, Supplier<X>> FACTORIES;
  static {
    FACTORIES = new HashMap<>();
    FACTORIES.put(1, A::new);
    FACTORIES.put(2, B::new);
  }

  public static X createObject(int type) {
    return Optional.ofNullable(FACTORIES.get(type))
      .map(Supplier::get)
      .orElse(null);
  }

由于您使用整数来标识类型,因此您可以非常简单地使用数组:

  private static final Supplier<X>[] FACTORIES = new Supplier[] { A::new, B::new };

  public static X createObject(int type) {
    return type > 0 && type <= FACTORIES.length ?
      FACTORIES[type - 1].get() :
      null;
  }