I\'m familiar with the idea and benefits of a static factory method, as described in Joshua Bloch\'s Effective Java:
My current favorite example of this pattern is Guava's ImmutableList. Instances of it can only be created by static factories or a builder. Here are some ways that this is advantageous:
ImmutableList
doesn't expose any public
or protected
constructors, it can be subclassed within the package while not allowing users to subclass it (and potentially break its immutability guarantee).ImmutableList.of()
factory method returns a singleton instance of EmptyImmutableList
. This demonstrates how a static factory method doesn't need to create a new instance if it doesn't have to.ImmutableList.of(E)
method returns an instance of SingletonImmutableList
which is optimized because it will only ever hold exactly 1 element.RegularImmutableList
.copyOf(Collection)
static factory method also does not always need to create a new instance... if the Collection
it is given is itself an ImmutableList
, it can just return that!