Pattern: Singleton

Synopsis

The Singleton pattern ensures that exactly one instance of a class exists and it provides a way to access that object.

Context

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.

Forces

There are two forces that affect the Singleton:

Solution

The Singleton class is easy to implement and involves just the one class. The main characteristics of the implementation are:

Consequences

Implementation

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

}

Related Patterns

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