单例模式(C++)

介绍

单例模式,顾名思义,就是保证一个类只一个对象.

单例模式可以分为懒汉模式和饿汉模式两种:

  • 懒汉模式:不到万不得已不去实例化对象,也就是在第一次使用到类实例时才会去实例化一个对象.访问量较小时,采用懒汉模式,可以达到时间换空间的效果.
  • 饿汉模式: 在定义单例对象时就初始化.访问量较大时,或者可能访问的线程较多时,采用饿汉模式,可以实现更好的性能.以空间换时间.

示例

懒汉模式:

class Singleton {
public:
    static Singleton* GetInstance();

private:
    Singleton() {}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    static Singleton* instance_;
    static std::mutex mutex_;
};

Singleton* Singleton::instance_ = nullptr;
std::mutex Singleton::mutex_;

Singleton* Singleton::GetInstance() {
    if(instance_ == nullptr) {
        mutex_.lock();
        if(instance_ == nullptr) {
            instance_ = new Singleton();
        }
        mutex_.unlock();
    }

    return instance_;
}

饿汉模式:

class Singleton {
public:
    static Singleton* GetInstance();

private:
    Singleton() {}
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    static Singleton* instance_;
};

Singleton* Singleton::instance_ = new Singleton();

Singleton* Singleton::GetInstance() {
    return instance_;
}

原文链接: https://www.cnblogs.com/xl2432/p/13140041.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    单例模式(C++)

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/355646

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午10:27
下一篇 2023年3月2日 上午10:27

相关推荐