Singleton

To ensure only one instance of the class should be created

Check list

  1. Define a private static variable in the "single instance" class.
  2. Define a public static member function in the class.
  3. Do "lazy initialization" (creation on first use) in the accessor function.
  4. Define all constructors to be protected or private.
  5. 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;
}

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment

Popular posts from this blog

STL Questions

Producer Consumer problem using mutex

Interview questions