When and how should we use a constructor
Foo bar = new Foo();
And when and how should we use getInstance() (static factory
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 typeboolean
). This method translates a boolean primitive value into aBoolean
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):
Disadvantages (still quoting the book):