Code
Design Pattern : Creational Pattern Singleton - by hackervalley - Monday 9th AugustDesign Pattern : Creational Pattern Singleton
Introduction
It’s important for some classes to have exactly one instance. For example have only one GUI, one engine.
To implement a singleton pattern, a common way is to define a class that has a protected constructor and a public static member function to create and retrieve an instance of the class.
Implementation
{
public:
static Singleton *GetInstance ();
protected:
Singleton(){};
private:
static Singleton *Instance;
};
Singleton *
Singleton::Instance = NULL;
Singleton *
Singleton::GetInstance ()
{
if (Instance == NULL)
Instance = new Singleton;
return Instance;
}
Example of singleton usage: Singleton *engine = Singleton::GetInstance ();
Conclusion
Singleton ensure to have only one instance, and provide a global point of access to a class.
DPCPSingleton.tar.bz2
BZip - 1 kb