單例模式又分爲懶漢式和餓漢式
#include<iostream>
#include<pthread.h>
using namespace std;
class Singleton
{
private:
static Singleton *mInstance;
static int handlecount;
private:
Singleton()
{
}
public:
static Singleton *GetInstance()
{
if(NULL == mInstance)
{
usleep(100000);
mInstance = new Singleton;
}
handlecount++;
return mInstance;
}
static int Gethandcount()
{
return handlecount;
}
int dele()
{
handlecount--;
if(handlecount==0 && mInstance != NULL)
{
delete mInstance;
mInstance = NULL;
}
return handlecount;
}
};
Singleton *Singleton::mInstance = NULL;
int Singleton::handlecount = 0;
void * create1(void *arg)
{
Singleton * s1=Singleton::GetInstance();
cout<<s1<<endl;
}
int main()
{
int ret;
pthread_t id[20];
for(int i=0;i < 20;i++)
{
ret = pthread_create(&id[i],NULL,create1,NULL);
if(ret != 0)
{
perror("pthread_create");
}
}
void *value;
for(int i = 0;i < 20;i++)
{
pthread_join(id[i],&value);
}
return 0;
}
答案是20個不一樣的地址。
而餓漢式
#include<iostream>
#include<pthread.h>
using namespace std;
class Singleton
{
private:
static Singleton *mInstance;
static int handlecount;
private:
Singleton()
{
}
public:
static Singleton *GetInstance()
{
handlecount++;
return mInstance;
}
static int Gethandcount()
{
return handlecount;
}
int dele()
{
handlecount--;
if(handlecount==0 && mInstance != NULL)
{
delete mInstance;
mInstance = NULL;
}
return handlecount;
}
};
Singleton *Singleton::mInstance = new Singleton;
int Singleton::handlecount = 0;
void * create1(void *arg)
{
Singleton * s1=Singleton::GetInstance();
cout<<s1<<endl;
}
int main()
{
int ret;
pthread_t id[20];
for(int i=0;i < 20;i++)
{
ret = pthread_create(&id[i],NULL,create1,NULL);
if(ret != 0)
{
perror("pthread_create");
}
}
void *value;
for(int i = 0;i < 20;i++)
{
pthread_join(id[i],&value);
}
return 0;
}
答案是20個相同的地址。
單例模式的作用是保證爲一個類只生成唯一的實例對象。也就是說,在整個程序空間中,該類只存在一個實例對象。
懶漢式和餓漢式的區別就在於懶漢式是在程序運行到那時纔會分配空間,而餓漢式則是已經提前分配好空間