Singleton

From Rosetta Code
Revision as of 03:08, 5 February 2008 by MikeMol (talk | contribs) (Created Global Singleton class)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Singleton
You are encouraged to solve this task according to the task description, using any language you may know.

A Global Singleton is a class of which only one instance exists within a program. Any attempt to use non-static members of the class involves performing operations on this one instance.

C++

Operating System: Microsoft Windows NT/XP/Vista

class Singleton
{
public:
     static Singleton* Instance()
     {
          // We need to ensure that we don't accidentally create two Singletons
          HANDLE hMutex = CreateMutex(NULL, FALSE, "MySingletonMutex");
          WaitForSingleObject(hMutex, INFINITE);

          // Create the instance of the class.
          // Since it's a static variable, if the class has already been created,
          // It won't be created again.
          static Singleton myInstance;

          // Release our mutex so that other application threads can use this function
          ReleaseMutex( hMutex );

          // Return a pointer to our mutex instance.
          return &myInstance;
     }

     // Any other public methods

protected:
     Singleton()
     {
          // Constructor code goes here.
     }
     ~Singleton()
     {
          // Destructor code goes here.
     }

     // And any other protected methods.
}