P
Pallav singh
1. its not executing display() properly ....just look to it
2. Suggest effective way to write MUTEX class at User level
#include <iostream.h>
using namespace std;
template<typename TYPE>
class Singleton
{
private :
Singleton() { cout<<" constructor Invoked "<< endl; }
~Singleton() { cout<<" Destructor Invoked "<<endl; }
Singleton(const Singleton<TYPE> & a)
{ cout<<" Copy Constructor Invoked "<<endl; }
const Singleton<TYPE> & operator = (const Singleton<TYPE> &);
static TYPE * instance;
static volatile long Flag; // Flag is volatile.
public :
static TYPE * GetInstance( void )
{
if( Flag == 0 )
{
// TO BE DONE Guard<Mutex> acquire();
if( Flag == 0 )
{
if( instance != NULL)
{ try
{ instance = new TYPE();}
catch(...)
{ cout <<"Creation of Object failed
"<<endl; }
}
cout<<" Instance Created Successfully \n";
Flag = 1;
// Mutex.release();
}
return instance;
}
else
{
cout<<" Returning the Already Created Instance \n";
return instance;
}
}
};
template<typename TYPE>
TYPE * Singleton<TYPE>::instance = 0 ;
template<typename TYPE>
volatile long Singleton<TYPE>::Flag = 0;
class A
{
public :
int i,j;
A(int i = 1 , int j = 1):i(i),j(i){}
void display()
{ cout<<" value of i "<< i <<" value of j "<< j <<endl; }
};
int main()
{
A * obj1 = Singleton<A>::GetInstance();
A * obj2 = Singleton<A>::GetInstance();
A * obj3 = Singleton<A>::GetInstance();
obj1->display();
//obj2->display();
//obj3->display();
// To check if it call destructor of Object
delete obj1;
delete obj2;
delete obj3;
}
2. Suggest effective way to write MUTEX class at User level
#include <iostream.h>
using namespace std;
template<typename TYPE>
class Singleton
{
private :
Singleton() { cout<<" constructor Invoked "<< endl; }
~Singleton() { cout<<" Destructor Invoked "<<endl; }
Singleton(const Singleton<TYPE> & a)
{ cout<<" Copy Constructor Invoked "<<endl; }
const Singleton<TYPE> & operator = (const Singleton<TYPE> &);
static TYPE * instance;
static volatile long Flag; // Flag is volatile.
public :
static TYPE * GetInstance( void )
{
if( Flag == 0 )
{
// TO BE DONE Guard<Mutex> acquire();
if( Flag == 0 )
{
if( instance != NULL)
{ try
{ instance = new TYPE();}
catch(...)
{ cout <<"Creation of Object failed
"<<endl; }
}
cout<<" Instance Created Successfully \n";
Flag = 1;
// Mutex.release();
}
return instance;
}
else
{
cout<<" Returning the Already Created Instance \n";
return instance;
}
}
};
template<typename TYPE>
TYPE * Singleton<TYPE>::instance = 0 ;
template<typename TYPE>
volatile long Singleton<TYPE>::Flag = 0;
class A
{
public :
int i,j;
A(int i = 1 , int j = 1):i(i),j(i){}
void display()
{ cout<<" value of i "<< i <<" value of j "<< j <<endl; }
};
int main()
{
A * obj1 = Singleton<A>::GetInstance();
A * obj2 = Singleton<A>::GetInstance();
A * obj3 = Singleton<A>::GetInstance();
obj1->display();
//obj2->display();
//obj3->display();
// To check if it call destructor of Object
delete obj1;
delete obj2;
delete obj3;
}