直接上源码吧:
#include
using namespace std;
//懒汉模式(未考虑线程安全,必要时加锁):
class singletion
{
private:
singletion()
{
cout<<“singletion()”<<endl;
}
static singletion* instance;
public:
static singletion GetInstance()
{
if(instance==NULL)
{
instance=new singletion();
}
return instance;
}
};
singletion singletion::instance =NULL;
//饿汉模式
class singletion1
{
private:
singletion1()
{
cout<<“singletion1()”<<endl;
}
static singletion1instance;
public:
static singletion1GetInstance()
{
return instance;
}
};
singletion1* singletion1::instance =new singletion1;
//测试代码
int main()
{
singletion *ptr = singletion::GetInstance();
singletion *ptr2 = singletion::GetInstance();
if(ptr= =ptr2)
{
cout<<“yes1”<<ptr<<endl;
}
else
{
cout<<“no1”<<endl;
}
singletion1 *ptr3 = singletion1::GetInstance();
singletion1 *ptr4 = singletion1::GetInstance();
if(ptr3==ptr4)
{
cout<<“yes”<<ptr3<<endl;
}
else
{
cout<<“no”<<endl;
}
return 0;
}
c++两种单例模式,源码
最新推荐文章于 2024-08-06 23:17:14 发布