Singleton design pattern


Published on

Name : Prasoon Dadhich
USN : 1MS09IS069


#include <iostream>

using namespace std;

class Singleton
static bool instanceFlag;
static Singleton *single;
//private constructor
static Singleton* getInstance();
void method();
instanceFlag = false;

bool Singleton::instanceFlag = false;
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
if(! instanceFlag)
single = new Singleton();
instanceFlag = true;
return single;
return single;

void Singleton::method()
cout << "Method of the singleton class" << endl;

int main()
Singleton *sc1,*sc2;
sc1 = Singleton::getInstance();
sc2 = Singleton::getInstance();

return 0;


If we create any object of this class then the static object (player) will be returned and assigned to the new object.
Finally only one object will be there. The point is not how many times something gets executed, the point is, that the work is done by a single instance of the the class. This is ensured by the class method Singleton::getInstance().

As you can see in the above code,Client can access any instance of the singleton only through the getInstance() method.Once an instance is created,the instanceFlag value becomes true and then any further objects pointers created will be given the reference to the same object that has been created.
Also,make sure you notice the presence of a private constructor.This ensures that no new objects of the class are created and that all the class pointers get the same reference to work on.

Published in: Design
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Singleton design pattern

  2. 2. Index Intent Structure Example program Explanation Participants Consequences Limitations Practical examples
  3. 3.  Intent Ensure a class only has one instance, andprovide a global point of access to it. Motivation It’s important for some classes to haveexactly one instance. Although there can be many printers in asystem, there should be only one printerspooler. There should be only one file system (or filesystem manager) and one window manager.
  4. 4. Structure
  5. 5.  Example program:public class TestSingleton {public static void main(String args[]) {// Get a reference to the single instance of Singleton.Singleton s = Singleton.instance();s.setData(34);System.out.println("First reference: " + s);System.out.println("Singleton data value is: " +s.getData());
  6. 6. // Get another reference to the Singleton.// Is it the same object?s = null;s = Singleton.instance();System.out.println("nSecond reference: " + s);System.out.println("Singleton data value is: " +s.getData());} }
  7. 7. The test program output is as shown:First reference:Singleton data value is: 34Second reference:Singleton data value is: 34
  8. 8.  Note that the singleton instance is only created whenneeded. This is called lazy instantiation. What if two threads concurrently invoke the instance()method? Any problems? If invoked concurrently, two instances of the singletonclass could be created. However, this could beprevented using the following 2 techniques:i) Make the instance() synchronized. Synchronizationis expensive, however, and it may have a negativeimpact on the performance. Moreover, it is reallyonly needed the first time the unique instance iscreated.
  9. 9. ii) Do an eager instantiation of the instance ratherthan a lazy instantiation. An eager class loaderloads all the classes comprising the applicationcode at startup. Such an implementation requiresa static initializer and is thread safe.
  10. 10. Singleton Participants Singleton - Defines an instance operation thatlets clients access its unique instance. Instanceis a class operation (static method). May beresponsible for creating its own uniqueinstance Client - Accesses a singleton instance solelythrough the singleton’s instance() method.
  11. 11. Singleton Consequences Controlled access to sole instance facilitatesstrict control over when and how the clientsaccess it. The singleton pattern is an improvement overglobal variables. It may be subclassed and it is easy to configurean instance of an application that extends thefunctionality of singleton at run-time. More flexible than class operations.
  12. 12. Singleton Limitations The main limitation of the singleton pattern isthat it permits the creation of only one instanceof the class, while most practical applicationsrequire multiple instances to be initialized. Furthermore, in case of singleton, the systemthreads fight to access the single instancethereby degrading the performance of theapplication.
  13. 13. Examples Cache – The cache can be used as a singletonobject, having a global point of reference forall future references to the cache object and theclient application uses this in-memory object. Configuration File – Any application has asingle point of reference through itsconfiguration files. Any changes to be made tothe application will have to be made via thissingle configuration file.
  14. 14. Thank You