单例模式是为了保证这个类只能被实例化一次,并提供一个全局访问的接口,整个程序模块都能通过这个接口访问这个唯一实例。
单例模式的懒汉版和饿汉版不同在于,前者是需要时再实例化,或者是系统运行时就进行了实例化。所以懒汉版需要考虑线程安全,而饿汉版不需要考虑线程安全。所以懒汉版需要加锁。
头文件 SingletonCase.h
#pragma once
#include<pthread.h>
class SingletonCase
{
public:
static void init(){
_instance = new SingletonCase();//初始化单例
};
//单例
static SingletonCase *instance(){
pthread_once(&_once,init);//保证只被初始化一次
return _instance;
}
private:
SingletonCase();
~SingletonCase();
//将拷贝构造和赋值构造变为私有函数,不提供被外界访问
SingletonCase(const SingletonCase&);//拷贝构造
const SingletonCase& operator=(const SingletonCase&);//赋值构造
static SingletonCase *_instance;
static pthread_once_t _once;//单例锁
};
源文件 SingletonCase.cpp
#include "SingletonCase.h"
//因为是懒汉模式,所以初始化位NULL
SingletonCase SingletonCase::_instance=NULL;
pthread_once_t SingletonCase::_once=PTHREAD_ONCE_INIT;