您好,欢迎来到筏尚旅游网。
搜索
您的当前位置:首页C++ 设计模式之单例模式

C++ 设计模式之单例模式

来源:筏尚旅游网

单例模式又分为饿汉模式和懒汉模式。

饿汉模式

饿汉模式是指类在加载时候就创建单例的对象。

// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
 
class Singleton {
    public:
        static Singleton* getInstance() {
            return instance;
        }   
    private:
        static Singleton* instance;
}; 
#endif

// singleton.cpp
#include "singleton.h"
Singleton* Singleton::instance = new Singleton();

懒汉模式

懒汉模式是指在使用时候才创建单例的对象。获取实例的时候先判断实例是否为空,为空则创建实例并返回这个实例,否则返回已创建的实例。

// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__

class Singleton {
    public:
        static Singleton* getInstance() {
            if (instance == nullptr) {
                instance = new Singleton();
            }
            return instance;
        }
    private:
        static Singleton* instance;
};
#endif

// singleton.cpp
#include "singleton.h"
Singleton* Singleton::instance = new Singleton();

加锁的饿汉模式

了解多线程安全的同学很容易看出上述代码的问题:如果多个线程同时进入 getInstance() 时候,实例都为空的话,则各自都会创建实例。很容易想到的一个方法就是加锁保证线程安全。

// singleton.h
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <mutex>

class Singleton {
    public:
        static Singleton* getInstance() {
            if (instance == nullptr) {
                m_mutex.lock();
                if (instance == nullptr) {
                    instance = new Singleton();
                }
                m_mutex.unlock();
            }
            return instance;
        }
    private:
        static Singleton* instance;
        static std::mutex m_mutex;
};
#endif

// singleton.cpp
#include "singleton.h"
Singleton* Singleton::instance = new Singleton();
std::mutex Singleton::m_mutex; 

Meyers 单例模式

C++11 规定了 local static 在多线程条件下的初始化行为,要求编译器保证内部静态变量的线程安全性。

#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <iostream>

class Singleton {
     private:
         Singleton () {
             std::cout << "Singleton ()" << std::endl;
         }
    public:
        static Singleton& getInstance() {
            static Singleton instance;
            return instance;
        }
};
#endif

可以测试如下:

 #include "singleton.h"
 #include <iostream>
 #include <thread>
 
 int main() {
 
     for (int i = 0; i < 10; ++i) {
         std::thread([]() {
             std::cout << &Singleton::getInstance() << std::endl;
         }).join();
     }   
     std::cout << &Singleton::getInstance() << std::endl;
 }

输出如下:

Singleton ()
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153
0x5588c12153

此外,拷贝构造函数和拷贝赋值操作可以使用 delete 标记来阻止编译器自动生成。

参考:

  • 《大话设计模式》
  • https://www.yuque.com/tomocat/txc11h/dq5xse

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- efsc.cn 版权所有 赣ICP备2024042792号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务