1 基本概念
单例Singleton是设计模式的一种,其特点是只提供唯一一个类的实例,具有全局变量的特点,在任何位置都可以通过接口获取到那个唯一实例;
- 全局只有一个实例:static 特性,同时禁止用户自己声明并定义实例(把构造函数设为 private)
- 线程安全
- 禁止赋值和拷贝
- 用户通过接口获取实例:使用 static 类成员函数
2 单例的实现
2.1 基础实现
我们很容易想到通过设置一个全局变量,就可以将某个类的实例限制为单例模式。
代码清单 2.1.1 全局变量方式实现单例模式
//Singleton.h#ifndef SINGLETON_H#define SINGLETON_H#include <iostream>using namespace std;class Singleton{public:Singleton();static Singleton * getInstance(void);void showinfo(void);};#endif
//Singleton.cppSingleton * Singleton::getInstance(void){if(gInstance == NULL){gInstance = new Singleton();}return gInstance;}Singleton::Singleton(){cout << "Singleton()" << endl;}void Singleton::showinfo(void){cout << "This is Singleton" << endl;}
然后在main函数中调用
#include "Singleton.h"int main(void){Singleton *s = Singleton::getInstance();Singleton *p = Singleton::getInstance();s->showinfo();p->showinfo();return 0;}
运行结果:
Singleton() This is Singleton This is Singleton
可见通过全局变量的限制,Singleton只能进行一次实例化的操作。但是在多个线程同时创建这个类的实例时,全局变量的这种方式显示是极不安全的。虽然概率极低,但是我们应该考虑到这种多个线程的场景。
代码清单 2.1.2 线程创建
#include "Singleton.h"#include <pthread.h>#include <unistd.h>void *start_routine_thread1(void *arg){cout<<"this is thread 1 ..."<<endl;Singleton *s = Singleton::getInstance();s->showinfo();return NULL;}void *start_routine_thread2(void *arg){cout<<"this is thread 2 ..."<<endl;Singleton *s = Singleton::getInstance();s->showinfo();return NULL;}int main(void){pthread_t thread1ID;pthread_t thread2ID;pthread_create(&thread1ID, NULL, start_routine_thread1, NULL);pthread_create(&thread2ID, NULL, start_routine_thread2, NULL);return 0;}
注意使用pthread时,g++编译时要链接pthread库
2.2 互斥锁防止临界冲突
为了防止多个线程同时调用一段代码,采用锁的机制来防止这类冲突,避免实例重复创建。
代码清单 2.2.1 增加互斥锁
#include "Singleton.h"#include <unistd.h>static Singleton * gInstance;static pthread_mutex_t g_tMutex = PTHREAD_MUTEX_INITIALIZER;Singleton * Singleton::getInstance(void){if(gInstance == NULL){pthread_mutex_lock(&g_tMutex);if(gInstance == NULL)gInstance = new Singleton();pthread_mutex_unlock(&g_tMutex);}return gInstance;}Singleton::Singleton(){cout << "Singleton()" << endl;}void Singleton::showinfo(void){cout << "This is Singleton" << endl;}
2.3 构造函数设置为private
为了防止用new方法来绕过getInstance接口,我们有必要把构造函数定义为私有成员。来防止用户直接使用该接口。
代码清单 2.3.1 隐藏构造函数
#ifndef SINGLETON_H#define SINGLETON_H#include <iostream>using namespace std;class Singleton{Singleton();public:static Singleton * getInstance(void);void showinfo(void);};#endif
2.4 将全局变量转化为类的静态成员
// 懒汉模式 饿汉模式
提前生成好,
