1 教科书里的单例模式

  我们都很清楚一个简单的单例模式该怎样去实现:构造函数声明为private或protect防止被外部函数实例化,内部保存一个private static的类指针保存唯一的实例,实例的动作由一个public的类方法代劳,该方法也返回单例类唯一的实例。

  上代码:  

class singleton
{
protected:
singleton(){}
private:
static singleton* p;
public:
static singleton* instance();
};
singleton* singleton::p = NULL;
singleton* singleton::instance()
{
if (p == NULL)
p = new singleton();
return p;
}

  这是一个很棒的实现,简单易懂。但这是一个完美的实现吗?不!该方法是线程不安全的,考虑两个线程同时首次调用instance方法且同时检测到p是NULL值,则两个线程会同时构造一个实例给p,这是严重的错误!同时,这也不是单例的唯一实现!

2 懒汉与饿汉

  单例大约有两种实现方法:懒汉与饿汉。

    • 懒汉:故名思义,不到万不得已就不会去实例化类,也就是说在第一次用到类实例的时候才会去实例化,所以上边的经典方法被归为懒汉实现;
    • 饿汉:饿了肯定要饥不择食。所以在单例类定义的时候就进行实例化。

  特点与选择:

    • 由于要进行线程同步,所以在访问量比较大,或者可能访问的线程比较多时,采用饿汉实现,可以实现更好的性能。这是以空间换时间。
    • 在访问量较小时,采用懒汉实现。这是以时间换空间。

3 线程安全的懒汉实现

  线程不安全,怎么办呢?最直观的方法:加锁。

  • 方法1:加锁的经典懒汉实现:

class singleton
{
protected:
singleton()
{
pthread_mutex_init(&mutex);
}
private:
static singleton* p;
public:
static pthread_mutex_t mutex;
static singleton* initance();
}; pthread_mutex_t singleton::mutex;
singleton* singleton::p = NULL;
singleton* singleton::initance()
{
if (p == NULL)
{
pthread_mutex_lock(&mutex);
if (p == NULL)
p = new singleton();
pthread_mutex_unlock(&mutex);
}
return p;
}
  • 方法2:内部静态变量的懒汉实现

  此方法也很容易实现,在instance函数里定义一个静态的实例,也可以保证拥有唯一实例,在返回时只需要返回其指针就可以了。推荐这种实现方法,真得非常简单。    

class singleton
{
protected:
singleton()
{
pthread_mutex_init(&mutex);
}
public:
static pthread_mutex_t mutex;
static singleton* initance();
int a;
}; pthread_mutex_t singleton::mutex;
singleton* singleton::initance()
{
pthread_mutex_lock(&mutex);
static singleton obj;
pthread_mutex_unlock(&mutex);
return &obj;
}

4 饿汉实现

  为什么我不讲“线程安全的饿汉实现”?因为饿汉实现本来就是线程安全的,不用加锁。为啥?自己想!

class singleton
{
protected:
singleton()
{}
private:
static singleton* p;
public:
static singleton* initance();
};
singleton* singleton::p = new singleton;
singleton* singleton::initance()
{
return p;
}

  是不是特别简单呢?

  以空间换时间,你说简单不简单?

  面试的时候,线程安全的单例模式怎么写?肯定怎么简单怎么写呀!饿汉模式反而最懒[正经脸]! 

最新文章

  1. 简述ES5 ES6
  2. 发送JS错误日志到服务器
  3. LinearRegression
  4. MVC学习系列——RazorViewEngine扩展
  5. mysqldump 的一些使用参数
  6. C++学习笔记7——模板
  7. NDK GDB 中打印vector , vector<vector <> >
  8. linux----suid\sgid
  9. webapp之路--理解viewport的使用
  10. Python基础篇(八)
  11. 记录python接口自动化测试--把操作excel文件的方法封装起来(第五目)
  12. 移动端1px问题处理方法
  13. git for linux使用
  14. 【ElasticSearch】 安装
  15. java.lang.RuntimeException: Unable to start activity ComponentInfo……AppCompat does not support the current theme features
  16. shell脚本实例-for实现批量主机的探测
  17. MVC基于角色权限控制--数据库设计
  18. 【Unity Shader】五、Shader纹理映射,及纹理的缩放和偏移
  19. 传统神经网络ANN训练算法总结
  20. Linux 下 JDK + Eclipse + PyDev 安装与配置

热门文章

  1. Android动画学习(二)——Tween Animation
  2. 使用phpstorm来进行svn提交
  3. 用JqueryUI的Dialog+IFrame实现仿模态窗口效果
  4. Asp.Net 使用Npoi导出Excel
  5. Gobblin采集kafka数据
  6. JConsole远程连接配置
  7. 实际案例:在现有代码中通过async/await实现并行
  8. sql常用语句(1)
  9. php中导入导出excel的原理
  10. jquery css事件编程 尺寸设置