单例模式,是设计模式的一种,是指一个类只有一个实例。
首先看实现的代码
- singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H
#include <stdio.h>
#include <pthread.h>
#include <malloc.h>
class Singleton {
public:
static Singleton *GetInstance();
private:
Singleton() {
printf("create singleton\n");
};
Singleton(const Singleton &) {
}; //禁止拷贝
Singleton & operator=(const Singleton &) {
}; //禁止赋值
private:
static Singleton *s;
};
extern pthread_mutex_t mutex;
#endif
- singleton.cpp
include "singleton.h"
Singleton *Singleton::s = NULL;
Singleton *Singleton::GetInstance()
{
if (s == NULL) {
pthread_mutex_lock(&mutex);
if (s == NULL) {
s = new Singleton();
}
pthread_mutex_unlock(&mutex);
}
return s;
}
- main.cpp
#include<stdio.h>
#include<pthread.h>
#include "singleton.h"
pthread_mutex_t mutex;
int main()
{
pthread_mutex_init(&mutex, NULL);
Singleton *s = Singleton::GetInstance();
Singleton *s1 = Singleton::GetInstance();
pthread_mutex_destroy(&mutex);
}
- 需要将类的构造函数,赋值构造函数,拷贝构造函数设为私有,另外,
当 if (s == NULL)这一行实际是一行优化代码,这一行目的是,每次get实例
时候,不需要去加锁,只有它为空的时候,才去加锁。