Suppliers

Beginning with Java 8 there's another approach to factory methods—factory fields!

Java 8 introduces function objects—called lambdas—which can be called as functions and stored in variables. (See Java 8 Lambdas.)

Instead of an abstract factory containing an abstract factory method—which needs to be implemented in separate concrete factory classes-- there is a single concrete factory containing a factory method field (i.e., a lambda), which can be set and reset like any field, but which can be called like any method. (Of course the applications of this go well beyond factory methods.)

A parameterless lambda that returns an object of type T has type java.util.function.Supplier<T>. The lambda is invoked by calling its get method:

Supplier<Double> supplier = ()->Math.random();
System.out.println(supplier.get()); // prints a random double between 0 and 1

Here's the FactoryPattern using lambdas:

FactoryDemo.java