When to use a Constructor and when to use getInstance() method (static factory methods)?

Everybody seems to focus on singletons while I think that the question is actually about constructor vs static factory methods.

This is actually Item 1: Consider static factory methods instead of constructors of Effective Java by Joshua Bloch:

Item 1: Consider static factory methods instead of constructors

The normal way for a class to allow a
client to obtain an instance of itself
is to provide a public constructor.
There is another technique that should
be a part of every programmer’s
toolkit. A class can provide a public
static factory method, which is simply a static method that returns an
instance of the class. Here’s a simple
example from Boolean (the boxed
primitive class for the primitive type
boolean). This method translates a
boolean primitive value into a
Boolean object reference:

public static Boolean valueOf(boolean b) {
    return b ? Boolean.TRUE : Boolean.FALSE;
}

Note that a static factory method is
not the same as the Factory Method
pattern from Design Patterns
[Gamma95, p. 107]. The static factory
method described in this item has no
direct equivalent in Design
Patterns
.

A class can provide its clients with
static factory methods instead of, or
in addition to, constructors.
Providing a static factory method
instead of a public constructor has
both advantages and disadvantages.

Advantages (quoting the book):

  • One advantage of static factory methods is that, unlike constructors, they have names.
  • A second advantage of static factory methods is that, unlike constructors, they are not required to create a new object each time they’re invoked.
  • A third advantage of static factory methods is that, unlike constructors, they can return an object of any subtype of their return type.
  • A fourth advantage of static factory methods is that they reduce the verbosity of creating parameterized type instances.

Disadvantages (still quoting the book):

  • The main disadvantage of providing only static factory methods is that
    classes without public or protected constructors cannot be subclassed.
  • A second disadvantage of static factory methods is that they are not
    readily distinguishable from other static methods.

Leave a Comment