Problem

An application needs one and only one instance of a core object.

Solution

Ensure that a class has only one instance. Provide a global interface to that instance.

Related Patterns

Discussion

The Singleton pattern is one of the most misused patterns in software engineering. When is Singleton unnecessary? Most of the time. The real problem with Singletons is they provide such a good excuse to not carefully consider the appropriate public and private elements of an object.

Examples

State, Abstract Factory, and Builder objects are often implemented as Singletons. When there is one and only one of an object, the Singleton pattern can be applied.

Code

This is a C++ snippet of a Singleton. The Singleton class is defined globally and will only have one instance of itself.

class Singleton{
  int val;
public:
  Singleton(int v = 0){val = v;}
  int get_value(){return val;}
  void set_value(int v){val = v;}
}
Singleton *singleton = 0;

void foo(){
  if(!singleton) singleton = new Singleton;
  singleton->set_value(1);
  cout << "foo: Singleton is " << singleton->get_value() << endl;
}
void bar(){
  if(!singleton) singleton = new Singleton;
  singleton->set_value(2);
  cout << "bar: Singleton is " << singleton->get_value() << endl;
}

int main(){
  if(!singleton) singleton = new Singleton;
  cout << "main: Singleton is " << singleton->get_value() << endl;
  foo(); bar();
}
// output:
main: Singleton is 0
foo: Singleton is 1
bar: Singleton is 2