Singleton

Revision as of 03:29, 5 February 2008 by MikeMol (talk | contribs) (Added non-thread-safe C++ version, subcategorized ObjC and C++ examples.)

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.

Task
Singleton
You are encouraged to solve this task according to the task description, using any language you may know.

C++

Thread-safe

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.
}

Non-Thread-Safe

This version doesn't require any operating-system or platform-specific features, but it is not safe in a multi-threaded environment.

class Singleton
{
public:
     static Singleton* Instance()
     {
          // Since it's a static variable, if the class has already been created,
          // It won't be created again.
          static Singleton myInstance;

          // 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.
}

Objective-C

Non-Thread-Safe

(Using Cocoa's NSObject as a base class)

// SomeSingleton.h
@interface SomeSingleton : NSObject
{
  // any instance variables
}

+ (SomeSingleton*)sharedInstance;

@end
// SomeSingleton.m
@implementation SomeSingleton

+ (SomeSingleton*) sharedInstance
{
   static sharedInstance = nil;
   if(!sharedInstance) {
      sharedInstance = [[SomeSingleton alloc] init];
   }
   return sharedInstance;
}

@end