What was the bit from the Highlander series? "There can be only one!"
The Singleton pattern enforces this idea. Hiding the details of creating the object from the calling class, a Singleton object forces the caller to access its functionality through a specialized interface. One advantage of this approach is that the caller will not need to track multiple objects over different calling objects.
While, supposedly, a Singleton object in C++ can be constructed in the manner as those in Java, I will be using a point to implement Singleton objects. The only disadvantage is that the user must manage the destruction of the object, and not depend on the scope of the Singleton.
Header File:
class Singleton
{
private:
Singleton(void);
~Singleton(void);
static Singleton *instance;
public:
static Singleton* getInstance(void);
static void Release(void);
};
Source:
#include "Singleton.h"
Singleton* Singleton::instance=NULL;
Singleton::Singleton(void)
{
//do stuff here
}
~Singleton::Singleton(void)
{
// clean up
}
Singleton* Singleton::getInstance(void)
{
if(instance == NULL){
instance = new Singleton();
}
return instance;
}
void Singleton::Release(void)
{
if(instance != NULL){
delete instance;
instance = NULL;
}
}
No comments:
Post a Comment