GofPatterns Gofpatterns  

Design Patterns  «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

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.