Singleton
To ensure only one instance of the class should be created
{
private:
mysingle()
{
}
mysingle(const mysingle &obj)
{
}
mysingle operator=(const mysingle &obj)
{
}
static mysingle *instance;
public:
static mysingle* getinstance();
void show()
{
cout<<"in show funtion"<<endl;
}
};
mysingle* mysingle::instance = NULL;
mysingle* mysingle::getinstance()
{
if(instance == NULL)
instance = new mysingle;
return instance;
}
int main()
{
mysingle::getinstance()->show();
return 0;
}
In multi thread environment, if someone wants to create singleton then simple singleton pattern doesn't work. for this locking mechanism is being used for this.
#include<iostream>
#include<pthread.h>
using namespace std;
class multiSingleton
{
multiSingleton()
{
}
multiSingleton(const multiSingleton&)
{
}
static multiSingleton *myInstance;
static pthread_mutex_t lock;
public:
static multiSingleton* getInstance()
{
if(myInstance == NULL)
{
pthread_mutex_lock(&lock);
if(myInstance == NULL)
myInstance = new multiSingleton();
pthread_mutex_unlock(&lock);
}
return myInstance;
}
void show()
{
cout<<"this is multi thread singleton"<<endl;
}
};
multiSingleton* multiSingleton::myInstance;
pthread_mutex_t multiSingleton::lock;
int main()
{
multiSingleton *obj;
obj = multiSingleton::getInstance();
obj->show();
return 0;
}
Check list
- Define a private
staticvariable in the "single instance" class. - Define a public
staticmember function in the class. - Do "lazy initialization" (creation on first use) in the accessor function.
- Define all constructors to be
protectedorprivate. - Clients may only use the accessor function to manipulate the Singleton.
Program
class mysingle{
private:
mysingle()
{
}
mysingle(const mysingle &obj)
{
}
mysingle operator=(const mysingle &obj)
{
}
static mysingle *instance;
public:
static mysingle* getinstance();
void show()
{
cout<<"in show funtion"<<endl;
}
};
mysingle* mysingle::instance = NULL;
mysingle* mysingle::getinstance()
{
if(instance == NULL)
instance = new mysingle;
return instance;
}
int main()
{
mysingle::getinstance()->show();
return 0;
}
In multi thread environment, if someone wants to create singleton then simple singleton pattern doesn't work. for this locking mechanism is being used for this.
#include<iostream>
#include<pthread.h>
using namespace std;
class multiSingleton
{
multiSingleton()
{
}
multiSingleton(const multiSingleton&)
{
}
static multiSingleton *myInstance;
static pthread_mutex_t lock;
public:
static multiSingleton* getInstance()
{
if(myInstance == NULL)
{
pthread_mutex_lock(&lock);
if(myInstance == NULL)
myInstance = new multiSingleton();
pthread_mutex_unlock(&lock);
}
return myInstance;
}
void show()
{
cout<<"this is multi thread singleton"<<endl;
}
};
multiSingleton* multiSingleton::myInstance;
pthread_mutex_t multiSingleton::lock;
int main()
{
multiSingleton *obj;
obj = multiSingleton::getInstance();
obj->show();
return 0;
}

This comment has been removed by a blog administrator.
ReplyDelete