himanshu tripathi
himanshu tripathi

Reputation: 31

What is the difference between a Singleton and static factory methods

I want to know if both singleton and static factory method create only one instance then why there are two concepts for same purpose?

Note: Here term "static factory method" is taken from Effective java book by Joshua bloch where he has written:

"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. This allows immutable classes (Item 15) to use preconstructed instances, or to cache instances as they’re constructed, and dispense them repeatedly to avoid creating unnecessary duplicate objects. The Boolean.valueOf(boolean) method illus- trates this technique: it never creates an object. This technique is similar to the Flyweight pattern [Gamma95, p. 195]. It can greatly improve performance if equivalent objects are requested often, especially if they are expensive to create. The ability of static factory methods to return the same object from repeated invocations allows classes to maintain strict control over what instances exist at any time. Classes that do this are said to be instance-controlled. There are several reasons to write instance-controlled classes. Instance control allows a class to guarantee that it is a singleton (Item 3) or noninstantiable (Item 4)"

Upvotes: 3

Views: 1971

Answers (2)

dimo414
dimo414

Reputation: 48874

The point being made by the line "they are not required to create a new object each time they’re invoked" is that (unlike new, which always creates a new object) a factory method could be implemented in some more clever way that reuses an existing object.

Take a look at the of() factory method in Guava's ImmutableList. This method returns "the" empty immutable list - there's no point constructing a new object every time of() is called, instead the same object is always returned. This is safe because any empty ImmutableList instance is functionally indistinguishable from any other empty instance.

Upvotes: 2

Edwin Buck
Edwin Buck

Reputation: 70949

A static factory method is a means of construction, it may return new instances, alternate subclasses of a type, wrap critical logging or registry, compose a number of items into an object, or (maybe) return back a single static instance.

A singleton obtained by any means always resolves back to the same instance. This means there is no variability.

Upvotes: 1

Related Questions