Singleton Pattern   «Prev  Next»
Lesson 3 Singleton: intent and motivation
ObjectiveIntent and Motivation for Singleton Patterns

Intent and Motivation for Singleton Design Patterns

The Singleton pattern is an object creational pattern. It is a creational pattern because it concerns itself with the creation of objects, more specifically with making sure more than one object is not created. It is an object pattern because it deals with the relationships between objects (specifically the unique instance object the class holds and other objects access) rather than with relations between classes and their subclasses.
The intent of the Singleton pattern is twofold:
  1. Guarantee that a class has only one instance
  2. Provide access to that instance


  1. Sometimes we want just a single instance of a class to exist in the system
  2. For example, we want just one window manager or just one factory for a family of products.
  3. We need to have that one instance easily accessible
  4. And we want to ensure that additional instances of the class can not be created

In this case, the motivation is that some real-world objects have no more than one instance. For example, most computers have only one audio output. No more than one sound can be played at a time. Therefore a class that represents the computer's audio device should have exactly one instance.
If there were two audio device objects, programmers could try to play multiple sounds simultaneously, generally with unpredictable and unwanted results. If there is only one audio device object, it can implement internal queuing as necessary to make sure that one sound file stops or finishes before it tries to play another. A queue could be shared between different audio device objects, but the overhead for maintaining the queue and communicating between the different objects is prohibitive.
Furthermore, since there is only one audio device to start with, that device might as well be set up as soon as the class is loaded. Initialization is simpler because you only have to do it once for the single instance of the AudioDevice class, rather than repeatedly for different instances.

Singleton Role

The purpose of the Singleton pattern is to ensure that there is only one instance of a class, and that there is a global access point to that object. The pattern ensures that the class is instantiated only once and that all requests are directed to that one and only object. Moreover, the object should not be created until it is actually needed. In the Singleton pattern, it is the class itself that is responsible for ensuring this constraint, not the clients of the class.