切换对象创建重构



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

我可以在没有开关语句的情况下做到这一点吗?

即:

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

太天真了,上课:

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

最新更新