Singleton design pattern
Upcoming SlideShare
Loading in...5
×
 

Singleton design pattern

on

  • 1,280 views

Name : Prasoon Dadhich ...

Name : Prasoon Dadhich
USN : 1MS09IS069

CODE


#include <iostream>

using namespace std;

class Singleton
{
private:
static bool instanceFlag;
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
instanceFlag = false;
}
};

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

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

int main()
{
Singleton *sc1,*sc2;
sc1 = Singleton::getInstance();
sc1->method();
sc2 = Singleton::getInstance();
sc2->method();

return 0;
}



Explanation

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.

Statistics

Views

Total Views
1,280
Views on SlideShare
1,280
Embed Views
0

Actions

Likes
0
Downloads
36
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Singleton design pattern Singleton design pattern Presentation Transcript

  • SINGLETONDESIGNPATTERN
  • Index Intent Structure Example program Explanation Participants Consequences Limitations Practical examples
  •  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. View slide
  • Structure View slide
  •  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());
  • // 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());} }
  • The test program output is as shown:First reference:Singleton data value is: 34Second reference:Singleton data value is: 34
  •  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.
  • 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.
  • 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.
  • 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.
  • 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.
  • 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.
  • Thank You