Static factory method

  • pattern to use when facing telescoping constructor
  • static method that returns an instance of the class

Example:
public static BigInteger valueOf(long val)

Advantages:

  1. They have names. Providing a name that describes what is being returned, makes this method easy to use and read. Imagine having a constructor with 7 parameters of a same type…
  2. They are not required to create a new object each time they are invoked. This offers a caching solution and can improve performance, since we can reuse objects with expensive creation. We can return immutable objects. This pattern enables us to create instance-controlled objects.
  3. They can return an object of any subtype of their return type. This flexibility enables us to return objects without making their classes public (hiding implementation). This technique can be used in interface-based-frameworks, since Java 8 allows interfaces to have static methods. This enables us to refer to the returned objects by it’s interface.
    Java 8 still requires static members of an interface to be public, while Java 9 allows private static methods. Static fields and member classes are still required to be public in Java 9.
  4. The class of the returned object can vary from call to call as a function of the input parameter (of course only the return type or it’s subtypes).
  5. The class of the returned object need not exists at the time of method being written.

Disadvantages:

  1. If only static factory method, class can not be subclassed (no public/protected constructor). This could be considered as an advantage since it encourages composition instead of inheritance.
  2. Methods are hard to find. They are not documented in Javadoc (unlike constructors).

Naming convention:
from – type-conversion (single parameter)
Example: DateTime dt = DateTime.from(instant);
to – aggregation (multiple parameters)
valueOf – alternative to from and to
Example: Boolean.valueOf(Boolean.TRUE)
instance, getInstance
create, newInstance – like instance and getInstance, but each call creates new instance
getType – like getInsatance but used when factory method is in another class
newType – like newInsatance but used when factory method is in another class
type – alternative to getType and newType