Intent:-
-Restrict the instantation of class to one object and provide global point of access to it.
Problem:-
-Application needs only one instance of an Object. additionally lazy initialization and global access is necessary.
Discussion:-
Make or Declare the class with its own instance as its static private data member. Provide a public static member function to create all initialization code and access to instance.
Subclassing of Singleton with "Public static member function" is not possible direct need some changes. make constructor as private. Use synchornisation to avoid multiple thread may create more than one object
Structure:-
UML diagram for Singleton

c++ code:-
below code is taken from:-
#include <iostream>
using namespace std;
class Singleton
{
private:
static Singleton *single;
Singleton()
{
//private constructor
}
public:
static Singleton* getInstance();
void method();
~Singleton()
{
}
};
Singleton* Singleton::single = NULL;
Singleton* Singleton::getInstance()
{
/// synchronized this part based on os
/// synchronized this part based on os
if(!single)
{
single = new Singleton();
}
///////synchronized end
///////synchronized end
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;
}
Singleton is not good as per
Singleton is not good as per
Singletons violated something called the 'Single Responsibility Principle' which states that every class you create should do one thing and one thing only because a Singleton has two distinct responsibilities: policing the instances of itself and providing configuration information.
Singletons were bad for memory management.
Singletons were bad for memory management.
source:http://geekswithblogs.net/AngelEyes/archive/2013/09/08/singleton-i-love-you-but-youre-bringing-me-down-re-uploaded.aspx
No comments:
Post a Comment