【设计模式】C++单例模式

实现单例的步骤

  1. 构造函数私有化。不能让外部访问构造函数。
  2. 增加静态私有的当前类的指针变量。
  3. 提供静态对外接口,可以让用户获得单例对象。

单例划分:1.懒汉式 2.饿汉式

//懒汉式,需要的时候再创建
class Singleton_lazy {
private:
    Singleton_lazy() {}
    static Singleton_lazy* getInstance() {
        if (pSingleton == NULL) {
            pSingleton = new Singleton_lazy;
        }
        return pSingleton;
    }
private:
    static Singleton_lazy* pSingleton;
};
//类外初始化
Singleton_lazy* Singleton_lazy::pSingleton = NULL;
//饿汉式,在main函数之前创建
class Singleton_hungry {
private:
    Singleton_hungry() {}
    static Singleton_hungry* getInstance() {
        return pSingleton;
    }
private:
    static Singleton_hungry* pSingleton;
};
//类外初始化
Singleton_hungry* Singleton_hungry::pSingleton = new Singleton_hungry;

原文链接: https://www.cnblogs.com/zhangjiuding/p/13188573.html

欢迎关注

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

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

    【设计模式】C++单例模式

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

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

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

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

(0)
上一篇 2023年3月2日 下午12:16
下一篇 2023年3月2日 下午12:17

相关推荐