Tuesday, March 3, 2015

Singleton pattern design and implementation

Singleton pattern is a design pattern that restricts the instantiate of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. 

One way of creating Singleton using Mutex

"A Mutex is essentially the same thing as a binary semaphore and sometimes uses the same basic implementation. The differences between them are in how they are used. While a binary semaphore may be used as a Mutex , a Mutex is a more specific use-case, which allows extra guarantees:"

Properties of Mutex:

  • Mutexes have a concept of an owner. Only the process that locked the Mutexis supposed to unlock it. If the owner is stored by the Mutexthis can be verified at runtime.
  • Mutexes may provide priority inversion safety. If the Mutexknows its current owner, it is possible to promote the priority of the owner whenever a higher-priority task starts waiting on the Mutex.
  • Mutexes may also provide deletion safety, where the process holding the Mutexcannot be accidentally deleted.
MFC implementation of Singleton using Mutex

  1.  Add a header file named LimitSingleInstance.h to the project.
  2. Add the following code in  LimitSingleInstance.h

#ifndef LimitSingleInstance_H
#define LimitSingleInstance_H

#include  

//This code is from Q243953 in case you lose the article and wonder
//where this code came from.
class CLimitSingleInstance
{
protected:
  DWORD  m_dwLastError;
  HANDLE m_hMutex;

public:
  CLimitSingleInstance(TCHAR *strMutexName)
  {
    //Make sure that you use a name that is unique for this application otherwise
    //two apps may think they are the same if they are using same name for
    //3rd parm to CreateMutex
    m_hMutex = CreateMutex(NULL, FALSE, strMutexName); //do early
    m_dwLastError = GetLastError(); //save for use later...
  }
   
  ~CLimitSingleInstance() 
  {
    if (m_hMutex)  //Do not forget to close handles.
    {
       CloseHandle(m_hMutex); //Do as late as possible.
       m_hMutex = NULL; //Good habit to be in.
    }
  }

  BOOL IsAnotherInstanceRunning() 
  {
    return (ERROR_ALREADY_EXISTS == m_dwLastError);
  }
};
#endif

3. In the application class InitInstance() method add the following code


CLimitSingleInstance g_SingleInstanceObj(TEXT("Global\\{AD3DB0CB-8197-4C9F-A425-40C75309A7D0}"));
BOOL CSingleTonApp::InitInstance()
{
if(g_SingleInstanceObj.IsAnotherInstanceRunning()){
AfxMessageBox(_T("Another Instance is Running"));
return FALSE;
}
//..... do something 
//.....
return TRUE;
}



4. The GUID value can be generated by using Tools Menu >> Create GUID >> Registry Format.

5. Now, only one application object instantiates for the Windows application class. So, there will be only instance of the application.
-

No comments: