建立型模式--單例模式
阿新 • • 發佈:2018-11-17
懶漢模式
#include <iostream>
#include <pthread.h>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance();
private:
Singleton();
~Singleton();
static Singleton *m_pInstance;
static pthread_mutex_t mutex;
};
Singleton *Singleton::m_pInstance = NULL ;
pthread_mutex_t Singleton::mutex = PTHREAD_MUTEX_INITIALIZER;
Singleton::Singleton()
{
pthread_mutex_init(&mutex, NULL);
}
Singleton *Singleton::getInstance()
{
if (m_pInstance == NULL)
{
pthread_mutex_lock(&mutex);
if (m_pInstance == NULL)
{
m_pInstance = new Singleton();
}
pthread_mutex_unlock(&mutex);
}
return m_pInstance;
}
Singleton::~Singleton()
{
if (m_pInstance != NULL)
{
delete m_pInstance;
}
}
int main()
{
Singleton *instance1 = Singleton::getInstance();
Singleton *instance2 = Singleton::getInstance();
if (instance1 == instance2)
{
cout << "instance1 == instance2" << endl;
}
return 0;
}
餓漢模式
#include <iostream>
using namespace std;
class Singleton
{
public:
static Singleton *getInstance();
private:
Singleton() {}
~Singleton();
static Singleton *m_pInstance;
};
Singleton* Singleton::m_pInstance = new Singleton();
Singleton* Singleton::getInstance()
{
return m_pInstance;
}
int main()
{
Singleton *instance1 = Singleton::getInstance();
Singleton *instance2 = Singleton::getInstance();
if (instance1 == instance2)
{
cout << "instance1 == instance2" << endl;
}
return 0;
}