The Singleton pattern ensures that exactly one instance of a class exists and it provides a way to access that object.
Sometimes you may want exactly one object of a particular type to exist. Usually, this class will be a central resource manager, such as a database manager, or something like that. You want to have all requests for the resource to go through this object and you want to make sure that only one of these objects exist. If two objects exist, they may interfere with each other, corrupting the resource, and causing potentially fatal errors in the system.
There are two forces that affect the Singleton:
- There must be exactly one instance of the class
- The instance must be (easily) accessible to all potential clients
The Singleton class is easy to implement and involves just the one class. The main characteristics of the implementation are:
- private constructor
- a single instance kept as a private member
- a static getter function to retrieve the instance
The following code shows the required items for implementing the Singleton pattern.
/**
* @author gpollice
*
* This class represents one a generic ResourceManager class to illustrate
* how to implement a Singleton.
* This implementation has the class as final, but that is not absolutely
* necessary.
*/
public final class ResourceManager {// The only instance of this class that can exist
private static final ResourceManager uniqueInstance = new ResourceManager();/**
* Constructor is private to ensure that no one can create
* a ResourceManager.
*/
private ResourceManager() {
// Insert constructor code here
}
/**
* Getter method for the instance.
* @return the unique instance of the ResourceManager class.
*/
public static ResourceManager getUniqueInstance() {
return uniqueInstance;
}
// ... other methods as normal}
Often used with Abstract Factory, Builder, and Prototype.
The Singleton is similar to a Cache manager, but with one object.
Modified:
28-Jan-2004
Gary Pollice