编写工厂方法最有效的方法是什么?

Mal*_*ose 3 java design-patterns factory factory-pattern effective-java

在大多数情况下,当我们编写工厂方法时,它是一堆if可以继续增长的条件.编写这种方法的最有效方法是什么(if条件最少)?

public A createA(final String id) {
    if (id.equals("A1")) {
      return new A1();
    }
    else if (id.equals("A2")) {
      return new A2();
    }
    return null;
  }
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 9

你可以使用Map<String, Supplier<A>>:

Map<String, Supplier<A>> map = new HashMap<>();
map.put("A1", () -> new A1());
map.put("A2", () -> new A2());

...

public A createA(final String id) {
    Supplier<A> supplier = map.get(id);
    if (supplier != null) {
        return supplier.get();
    }
    throw new IllegalArgumentException("unknown id: " + id);
}
Run Code Online (Sandbox Code Playgroud)

它使用标准的Java 8 Supplier接口,使用Java 8 lambda语法,但您当然可以定义自己的Supplier接口,并使用匿名内部类创建实例.