单例模式

单例模式是指在整个生命周期里,一个类只能实例化一次,该类是唯一的
单例模式可以分为懒汉模式和饿汉模式,
懒汉模式是指:系统运行时,实例不存在,只有在需要的时候才会去创建
饿汉模式是指:系统一运行,就创建实例,使用时直接调用即可
单例类特点:构造函数和析构都是private,防止在外部构造、析构;同理拷贝构造和赋值也是private的;单例类提供静态函数获取实例
一、懒汉模式

class singleton_test {
public:
    static singleton_test* get_instance() {
        if (pInstance_ == nullptr) {
            pInstance_ = new singleton_test();
        }
        return pInstance_;
    }

    static void delete_instance() {
        if (pInstance_ == nullptr) {
            delete pInstance_;
            pInstance_ = nullptr;
        }
    }
private:
    singleton_test() {}
    ~singleton_test() {}
    singleton_test(const singleton_test& other){}
    singleton_test& operator=(const singleton_test& other){}
private:
    static singleton_test* pInstance_;
};

singleton_test* singleton_test::pInstance_ = nullptr;

普通的懒汉模式,在多线程情况下,会发生多次创建,不是线程安全的,若想实现线程安全,则需要加锁。

class singleton_test {
public:
    static singleton_test* get_instance() {
        if (pInstance_ == nullptr) {
            std::unique_lock<std::mutex> lk(mt_);
            if (pInstance_ == nullptr) {
                pInstance_ = new singleton_test();
            }
        }
        return pInstance_;
    }

    static void delete_instance() {
        std::unique_lock<std::mutex> lk(mt_);
        if (pInstance_ == nullptr) {
            delete pInstance_;
            pInstance_ = nullptr;
        }
    }
private:
    singleton_test() {}
    ~singleton_test() {}
    singleton_test(const singleton_test& other){}
    singleton_test& operator=(const singleton_test& other){}
private:
    static singleton_test* pInstance_;
    static std::mutex mt_;
};

singleton_test* singleton_test::pInstance_ = nullptr;
std::mutex singleton_test::mt_;

二、饿汉模式

class singleton_test {
public:
    static singleton_test& get_instance() {
        static singleton_test instance;
        return instance;
    }

private:
    singleton_test() {}
    ~singleton_test() {}
    singleton_test(const singleton_test& other){}
    singleton_test& operator=(const singleton_test& other){}
};

饿汉模式是线程安全的,整个过程无需加锁。
懒汉是以时间换空间,适合访问量较小或者单线程,线程比较少的情况
饿汉是以空间换时间,适合访问量较大或者线程比较多的情况

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 什么是线程安全? 在拥有共享数据的多条线程并行执行的程序中,线程安全的代码会通过同步机制保证各个线程都可以正常且正...
    小林coding阅读 552评论 0 1
  • 有些对象我们只需要一个,比如配置文件、工具类、线程池、缓存、日志对象等。如果创建多个实例,就会导致许多问题,比如占...
    不知名的蛋挞阅读 435评论 0 0
  • 单例模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建,这个类提供了一种访问其唯一的对象的...
    静默Myself阅读 254评论 0 0
  • 目录: 文章目录 前言 一 单例模式简介 1.1 定义 1.2 为什么要用单例模式呢? 1.3 为什么不使用全局变...
    xiaoyang08阅读 1,202评论 0 2
  • 今天感恩节哎,感谢一直在我身边的亲朋好友。感恩相遇!感恩不离不弃。 中午开了第一次的党会,身份的转变要...
    迷月闪星情阅读 10,617评论 0 11