Search This Blog

Tuesday, February 19, 2013

Singleton Class in C++


Singleton pattern is a design pattern that restricts the instantiation of a class to one object.

Application:
  • This pattern can be used in "Database class" to that insert and retrieve record's in threads.
  • Can be used in Logger class.
How to create?
  • Define the constructor as private.
  • Declare copy constructor and Assignment operator as private to avoid creating copy of object
Sample 1( Allocating memory dynamically with new operator):

 
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;


class Singleton
{
private:
    static Singleton *m_ptrInstance;
    Singleton(){};
    Singleton(Singleton const&);             
    void operator=(Singleton const&);

public:
    static Singleton* GetInstance()
    {
        if(m_ptrInstance==NULL)
        {
            m_ptrInstance=new Singleton();
        }
        return m_ptrInstance;
    }
    void Display()
    {
        cout<<"This is singleton class"; 
    }
};
Singleton* Singleton::m_ptrInstance=NULL;


int _tmain(int argc, _TCHAR* argv[])
{
    //How to call    
    Singleton::GetInstance()->Display();
    getch();
    return 0;
}
 
Sample 2( Without allocating memory dynamically with new operator):

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;


class Singleton
{
private:
    Singleton(){}
    Singleton(Singleton const&);             
    void operator=(Singleton const&);

public:
    static Singleton& GetInstance()
    {
        static Singleton _instance;
        return _instance;
    }
    void Display()
    {
        cout<<"This is singleton class"; 
    }
};


int _tmain(int argc, _TCHAR* argv[])
{
    //How to call    
    Singleton::GetInstance().Display();
    getch();
    return 0;
}

No comments:

Post a Comment