Singleton Design Pattern


GoF Statement: Ensures a class has only one instance, and provides a global point of access to it.
Category: Creational
UML Diagram:  
Description of the Demonstration:

In this demonstration the class SingletonDemo has a private constructor making it impossible to directly instantiate an instance. It also contains a public static function called getInstance. When a function is declared as static in a class you do not need an instance of the class in order to call that function. The syntax for such a call is SingletonDemo::getInstance(). In this static function there is a static variable: SingletonDemo *instance = NULL; The first time getInstance is called the pointer instance is NULL so a single instance of SingletonDemo is created and the pointer to that returned. Any other call to getInstance will find the variable instance not NULL so the pointer to the single instance of SingletonDemo will be again returned.


Code:

Click here to download a zip file containing all the source files and an executable of the Demonstration. See the _ReadMe.txt file in the zip.