单例模式分为饿汉模式与懒汉模式,下面分别对其进行实现:
#include <iostream>
#include <vector>
#include <string>
#include <mutex>
#include <pthread.h>
using namespace std;
// 单例饿汉模式
class Singleton {
private:
Singleton() {}
static Singleton* instance;
public:
static Singleton* getInstance() {
return instance;
}
static void Destroy() {
delete instance;
instance = nullptr;
}
};
Singleton* Singleton::instance = new Singleton();
// 单例懒汉模式
class Singleton {
private:
Singleton() {}
static Singleton* instance;
static pthread_mutex_t mLock;
public:
static Singleton* getInstance() {
pthread_mutex_lock(&mLock);
if (instance == nullptr) {
instance = new Singleton();
}
pthread_mutex_unlock(&mLock);
return instance;
}
static void Destroy() {
pthread_mutex_lock(&mLock);
delete instance;
instance = nullptr;
pthread_mutex_unlock(&mLock);
}
};
Singleton* Singleton::instance = nullptr;
pthread_mutex_t Singleton::mLock = PTHREAD_MUTEX_INITIALIZER;
int main()
{
Singleton* A = Singleton::getInstance();
cout << " " << endl;
return 0;
}
|