singleton

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.






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值