Singleton pattern
The singleton design pattern is designed to restrict instantiation of a class to one (or a few) objects. This is useful when the services provided by the class only require one or a few instances of the class to be in existence or when only one instance of the class should be in existence at any one time.
The singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist. If one does exist it returns a reference to the object that already exists. To make sure that the object cannot be instantiated any other way the constructor is made either private or protected.
The singleton pattern can have problems in multi-threaded applications. If both threads execute the creation method at the same time when a singleton does not yet exist, they both do a check for an instance of the singleton and then both create a new one. This creates problems because you may require that no more than a certain number on the singleton be created.
It was originally thought that a technique called double-checked locking could be used to keep the singleton from creating too many instances of itself. This technique has been proven to fail on multi-processor computers. The real solution depends on the programming language you choose. It probobly involves tweaking code so that a check like this is not done and language specific constructs are used.
A Java solution is as follows (see the Q&A link in external links):
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor supresses // default public constructor private Singleton() {}
public static Singleton getInstance() { return INSTANCE; } }
External Links
- A Q&A page (java.sun.com)