2019-10-20 10:48:24 +00:00
|
|
|
#ifndef __SINGLETON_H__
|
|
|
|
#define __SINGLETON_H__
|
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
#include <string.h>
|
|
|
|
#include <mutex>
|
|
|
|
using namespace std;
|
|
|
|
|
2021-09-10 07:55:18 +00:00
|
|
|
class Singleton_Lazy
|
2019-10-20 10:48:24 +00:00
|
|
|
{
|
|
|
|
public:
|
2021-09-10 07:55:18 +00:00
|
|
|
static Singleton_Lazy* getInstance(){
|
|
|
|
printf("This is Singleton Lazy mode...\n");
|
2019-10-20 10:48:24 +00:00
|
|
|
if (instance == NULL){
|
|
|
|
m_mutex.lock();
|
|
|
|
if (instance == NULL){
|
2021-09-10 07:22:43 +00:00
|
|
|
printf("创建新的实例\n");
|
2021-09-10 07:55:18 +00:00
|
|
|
instance = new Singleton_Lazy();
|
2019-10-20 10:48:24 +00:00
|
|
|
}
|
|
|
|
m_mutex.unlock();
|
|
|
|
}
|
|
|
|
return instance;
|
|
|
|
}
|
|
|
|
private:
|
2021-09-10 07:55:18 +00:00
|
|
|
Singleton_Lazy(){}
|
2019-10-20 10:48:24 +00:00
|
|
|
|
2021-09-10 07:55:18 +00:00
|
|
|
static Singleton_Lazy* instance;
|
2019-10-20 10:48:24 +00:00
|
|
|
static std::mutex m_mutex;
|
|
|
|
};
|
|
|
|
|
2021-09-10 07:55:18 +00:00
|
|
|
Singleton_Lazy* Singleton_Lazy::instance = NULL;
|
|
|
|
std::mutex Singleton_Lazy::m_mutex;
|
|
|
|
|
|
|
|
|
|
|
|
class Singleton_Hungry
|
|
|
|
{
|
|
|
|
public:
|
|
|
|
static Singleton_Hungry* getInstance()
|
|
|
|
{
|
|
|
|
printf("This Singleton Hungry mode...\n");
|
|
|
|
return instance;
|
|
|
|
}
|
|
|
|
private:
|
|
|
|
Singleton_Hungry() {}
|
|
|
|
static Singleton_Hungry* instance;
|
|
|
|
};
|
|
|
|
|
|
|
|
Singleton_Hungry* Singleton_Hungry::instance = new Singleton_Hungry;
|
2019-10-20 10:48:24 +00:00
|
|
|
|
|
|
|
#endif //__SINGLETON_H__
|