Context:

  • A software module (in languages that do not support modularity).
  • A generally available part of the programming infrastructure whose existence is taken for granted by the programmers who use it.
  • A non-procedural flow of control implicit in the construction of infrastructure components prior to the main program.

Challenge:

  • To guarantee the existence of only one singleton object.
  • To complete the construction of the singleton instance prior to its first use.

Skill:

Participants:

Client:

Uses the singleton object.

Singleton class:

Allows access to the singleton instance. Responsible for creating it by default.

Signature:

Added static instance method, static singleton instance, private constructor and possibly destructor.

Known issues:

  1. If never used, the singleton constructor will never be invoked (which is not normally a reason for concern).
  2. Automatic disposal of the Singleton object. Where automatic garbage collection is not supported, the Singleton destructor will never be invoked. This is remedied (e.g. Meyers) by declaring the singleton object as a static variable in the instance method. The singleton destructor is invoked in the opposite order to that of the singleton constructor. It is the recommended to check that the singleton is not invoked after already being destroyed.
  3. Synchronizing Singleton access. In a multi-threaded application, two simultaneous accesses to the singleton may result in two instances of the singleton, one being useless. To prevent this, either the entire instance method or only in the first time allocation block are to be synchronized. The latter is double-checked as precaution.

Used by:

Factories, flyweights, dispatchers and similar globally available resource-management and synchronization mechanisms.

Sources:

GOF, Meyers.

Scope:

Languages that do not support modularity.