Tuesday 3 March 2009

The Singleton class

Singletons are not uncommon in large projects. The main advantage being that they act like static class but are not really static. They are only created when being used and can be deleted as well.

Here is an example of Singleton class:

Singleton.h file

class aSingletonClass
{

public
:
//method to get Instance of class
static aSingletonClass *getInstance( void )
{

//Note that the class is only created when this method is called first time
if(!instance_)
instance_ = new aSingletonClass;
return
instance_;
}

//method to delete Instance of class
static void deleteInstance( void )
{

if
(instance_)
delete
instance_;
instance_ = NULL; //important as this can create dead reference problems
}

private
:
//variable to store the instance of singleton
static aSingletonClass *instance_;
//default constructor should be private to prevent instantiation
aSingletonClass() {};
//destructor should be made private so no one can delete this accidently
~aSingletonClass() {};
//We also need to prevent copy being created of the object
aSingletonClass(const aSingletonClass&);
};
//mandatory or else error in compiling





Singleton.cpp file

/*
Singleton implies that there is only a single instance of this class
In simple terms this looks like a static class but thats not true.
*/

#include <iostream>
#include "Singleton.h"

using namespace
std;

aSingletonClass* aSingletonClass::instance_ = NULL;

int
main()
{

aSingletonClass *someVar = NULL;
//Create Instance
someVar = aSingletonClass::getInstance();

//aSingletonClass *anotherVar = new aSingletonClass; -- Not possible
//delete someVar; -- Not possible

//delete the Singleton class
aSingletonClass::deleteInstance();

return
0;
}


2 comments:

  1. getInstance() doesn't need a lock? Particularly if the constructor does a lot (which it doesn't in this case), it seems like two calls to get instance could cause parallel construction...

    ReplyDelete
  2. @Anonymous...I agree..Singleton pattern by itself is not thread-safe...Hence, if it is used by multi-threaded application, synchronization lock is necessary (regardless of constructor "does a lot" or not)...

    ReplyDelete