C++ singleton design patterns
singleton class
(1) guarantee a single instance
(2)provide a global access to the single instance.
In the GOF ,The way to implement the singleton is to use a private static pointer to pointer the only instance,and have a public getinstance() to get this instance.
steps:
1.move construct to private,nobody can make another object.
2.declare static instance variable to represent singleton.
3.provide a static access function to get ,definition of the static instance;
code :
class Random{
public:
static Random* getInstance()
{
if (!instance)instance=new Random;
return instance;
}
int operator()(int a,int b)
{
return (rand()%b+a);
}
private:
static Random* instance;
Random(){
int seed=time(0);
srand(seed);
};
Random& operator=(const Random&);
};
Random * Random::instance=NULL;
int _tmain(int argc, _TCHAR* argv[])
{ Random *random=Random::getInstance();
cout<<(*random)(1,100)<<endl;
return 0;
}
second method:
class Random{
public:
static Random& getInstance()
{
static Random random;
return random;
}
int operator()(int a,int b)
{
return (rand()%b+a);
}
private:
//static Random& instance;
Random(){
int seed=time(0);
srand(seed);
};
Random& operator=(const Random&);
};
//Random* Random::instance=NULL;
int _tmain(int argc, _TCHAR* argv[])
{ Random& random=Random::getInstance();
cout<<(random)(1,100)<<endl;
return 0;
}
if a static variable is local to a class,it must be define in somewhere( generally outside the class ),if a static variable is local to a function ,the complier
will help you to care.