JavaRanch Home    
 
This page:         last edited 28 May 2010         What's Changed?         Edit

Singleton Pattern   

Not the most important topic, but many questions relate to the singleton pattern. It's a deceptively simple pattern with subtle problems (to the point that some call it an AntiPattern?). Forum regulars often suggest that you Just Create One and use Dependency Injection to get it into the system.



A singleton is a class of which there cannot be multiple instances. It is one of the GangOfFour DesignPatterns.

In contrast to a class with all static methods (often called helper class), the singleton pattern encapsulates the knowledge of how many instances and of which actual class are used, thereby providing the option of making use of polymorphism. That is, you can change the implementation used for the Singleton based on some external stimulus (property file or something) without the clients even noticing.

Related Forum Threads:

Other Resources:



If you are thinking of using the singleton pattern, resist with all your might. It is one of the easiest DesignPatterns to understand, probably the most popular, and definitely the most abused. Use a singleton only if there is a fundamental reason inherent to your problem or your design why there can only be one instance of your class. "I need only one instance in this application" is not a fundamental reason: using a singleton will unnecessary constrain the evolution and reuse of your code, and also makes it harder to understand because you're giving your reader the wrong signals. "I need easy access to shared data using a static method" is also not a valid reason: an InversionOfControl framework such as the SpringFramework or PicoContainer? is a much better way to go about that. -- PeterDenHaan


JavaRanchContact us — Copyright © 1998-2014 Paul Wheaton