Enum factory using Java 8 supplier

782 views Asked by At

I am trying to create objects (implement factory pattern) using Java 8 lambda and Supplier interface.

public static void main(final String[] args) {
    FactoryEnum.getEnumByClassName("CLASS_A").getSupplier().execute();
    FactoryEnum.getEnumByClassName("CLASS_B").getSupplier().execute();
  }

enum FactoryEnum {

  CLASS_A(() -> A::new),

  CLASS_B(() -> B::new);

  private final Supplier<IConverter> supplier;

  FactoryEnum(final Supplier<IConverter> supplier) {
    this.supplier = supplier;
  }

  public static FactoryEnum getEnumByClassName(final String className) {
    return FactoryEnum.valueOf(className);
  }

  public IConverter getSupplier() {
    return supplier.get();
  }
}

interface IConverter {

  void execute();
}

class A implements IConverter {

  @Override
  public void execute() {

    System.out.println("Inside A"); //$NON-NLS-1$
  }

}

class B implements IConverter {

  @Override
  public void execute() {
    System.out.println("Inside B");
  }

}

When I call FactoryEnum.getEnumByClassName("CLASS_A").getSupplier().execute() I was expecting this to return an newly created Object of Class A and FactoryEnum.getEnumByClassName("CLASS_A").getSupplier().execute() and this to return newly created object of Class B. While it is returning me an Lambda. Why is it returning lambda rather then an Object of IConverter. And how I can get that?

1

There are 1 answers

1
Andrew Tobilko On BEST ANSWER
CLASS_A(() -> A::new)

means

CLASS_A(() -> { return A::new; })

which means

CLASS_A(() -> { return () -> { new A(); }; })

which isn't what you were trying to convey.

Try

CLASS_A(A::new)