Showing posts with label templates. Show all posts
Showing posts with label templates. Show all posts

Monday, June 11, 2007

Unique instance creator using templates C++

I am presenting an idea to create a unique instance of an object using templates.. This is very similar to Singleton design pattern..
The code may be look like this

class UniqueFactory

{

private :

   UniqueFactory()
   {
   }
public :

   static T * Instance()
   { 
        static T* ptr = new T();
        return ptr;
   }
};
So it will give the same instance of the object always.. For example
int *pInst = UniqueFactory<int>::Instance();
*pInst = 11;
pInst = UniqueFactory<int>::Instance();
*pInst , points to the same unique instance.
Another example is ( UserData can be any struct or class etc. )
UserData *pData = UniqueFactory<UserData>::Instance();
Hopes you may like it..!!