Ensure a class only has one instance and provide a global point of access to it. (GoF)
A system allows a single user to log in at a time. The currently logged-in user is represented by an object, an instance of a User class, that contains all the information needed throughout the system about the user including their access level, their rights and permissions in the system, etc.
Different parts of the system will need access to this object to determine what this particular user should be allowed to do, to view, what elements should and should not appear on a menu in the UI, what parts of the database should be made available, etc.
The instance could be passed to every part of the system that needs access to it, but this can be laborious, error-prone, and can produce potential redundancies. If it is made a Singleton instead, then any part of the system that needs access to it will cleanly retrieve it for itself.
Qualities and principles
The Singleton aspect of an object ensures there is only one instance, reflecting the needs of clients to interact with a shared resource. Although the typical Singleton is concrete, there is no coupling to this fact in clients as an abstract type can also have a getInstance() method.
A unit test can call getInstance() twice and assert that the object obtained is the same both times.
Questions and concerns
Since any part of the system can obtain the same instance of the Singleton, care must be taken to ensure that it contains no state that can be both read and written. If one part of the system can read the state and another can write it, then this creates uncontrolled coupling.
The Singleton is not inherently thread safe. When getInstance() is called for the first time, the creation of the instance takes time to complete, and if a second thread enters the method during this period a second instance could result. Locking the method is one way to alleviate this, but there are other options (see below).
Facades are often Singletons since they tend to be heavyweight objects, and we may want to enforce they are not built before needed and are never built multiple times.
Visit the Net Objectives Pattern Repository: The Singleton Pattern
This is Scott Bain. Visit us at www.netobjectives.com.