Singleton
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
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. }
Objective-C
(Using Cocoa's NSObject as a base class)
// SomeSingleton.h @interface SomeSingleton : NSObject { // any instance variables } + (SomeSingleton*)sharedInstance; @end
// SomeSingleton.m @implementation SomeSingleton + (GameController*) sharedInstance { static sharedInstance = nil; if(!sharedInstance) { sharedInstance = [[SomeSingleton alloc] init]; } return sharedInstance; } @end