当前位置: 首页 > news >正文

单例模式(懒汉模式/饿汉模式)

相关概念参考:【C++】C++ 单例模式总结(5种单例实现方法)_单例模式c++实现-CSDN博客

#include<iostream>

class LazySingle{
public:
    static LazySingle& getInstance(){
        static LazySingle instance;
        return instance;
    }

    void hello(){
        std::cout<<"Congratulations"<<std::endl;
    }

private:
    LazySingle(){};
};
class LazySinglePtr{
    public:
        static LazySinglePtr* getInstance(){
            static LazySinglePtr instance;
            return &instance;
        }
    
        void hello(){
            std::cout<<"Congratulations"<<std::endl;
        }
    
    private:
        LazySinglePtr(){};
};

class HungrySingle{
public:
    static HungrySingle& getInstance(){
        return instance_;
    }

private:
    static HungrySingle instance_;
    HungrySingle(){};
};

HungrySingle  HungrySingle::instance_;

int main(){
    std::cout<<"懒汉引用模式:"<<std::endl;
    auto& lazy1=LazySingle::getInstance();
    LazySingle& lazy2=LazySingle::getInstance();
    std::cout<<" lzay1="<<&lazy1<<" lzay2="<<&lazy2<<" instance="<<&LazySingle::getInstance()<<std::endl;
    lazy1.hello();

    std::cout<<"懒汉指针模式:"<<std::endl;
    auto lazyptr1=LazySinglePtr::getInstance();
    LazySinglePtr* lazyptr2=LazySinglePtr::getInstance();
    std::cout<<" lzay1="<<lazyptr1<<" lzay2="<<lazyptr2<<" instance="<<LazySinglePtr::getInstance()<<std::endl;
    lazyptr1->hello();
    
    std::cout<<"饿汉模式:"<<std::endl;
    HungrySingle& hungry1=HungrySingle::getInstance();
    HungrySingle& hungry2=HungrySingle::getInstance();
    std::cout<<" hungry1="<<&hungry1<<" hungry2="<<&hungry2<<" instance="<<&HungrySingle::getInstance()<<std::endl;

    return 0;
    
}

输出:

懒汉引用模式:
 lzay1=0x7ff61a279e90 lzay2=0x7ff61a279e90 instance=0x7ff61a279e90
Congratulations
懒汉指针模式:
 lzay1=0x7ff61a279ee0 lzay2=0x7ff61a279ee0 instance=0x7ff61a279ee0
Congratulations
饿汉模式:
 hungry1=0x7ff61a2aa030 hungry2=0x7ff61a2aa030 instance=0x7ff61a2aa030

 

http://www.dtcms.com/a/105588.html

相关文章:

  • 服务器数据恢复—误格式化NTFS文件系统分区别慌,NTFS数据复活秘籍
  • linux ubuntu下查询包是否包含某个工具
  • 移远通信推出超小Wi-Fi+BLE模组FGM842D系列,赋能智能家居与工业物联网高效互联
  • 【Easylive】MyBatis 批量插入或更新语句解析insertOrUpdateBatch
  • 12.小节
  • 关于React Redux
  • 【3. 软件工程】3.0 软件工程概述
  • Android View事件分发机制深度解析
  • QuecPython 的 VScode 环境搭建和使用教程
  • IS-IS认证
  • MySQL日志管理
  • NVR接入录像回放平台EasyCVR视频融合平台城市/乡镇污水处理厂解决方案
  • 计算机等级考试数据库三级(笔记2)
  • 032-overlayYUV
  • 深入解析Kapt —— Kotlin Annotation Processing Tool 技术博客
  • 使用 Portainer 轻松管理 Docker 环境:完整安装与使用指南
  • MD编辑器中的段落缩进怎么操作
  • 链路追踪Skywalking
  • QT实现四则运算计算器(QT实操1)
  • 多台服务器上docker部署 Redis 集群
  • Spring Boot @RequestParam 解析参数时的常见问题及解决方案
  • linux基本命令(2)--进程命令PS
  • Linux更换挂载nfs迁移数据流程
  • 使用AOP技术实现Java通用接口验签工具
  • 【vue】editor富文本输入全英文,谷歌浏览器:元素不会自动换行bug
  • 为什么hash%length 和hashlength-1 的值是一样的(当length=2的幂次方)
  • Java:三十年演进,永续创新的编程传奇
  • 【SPP】蓝牙 SDP 协议在SPP中的互操作性解析
  • vue2修改窗口字典回显
  • 四款高效数据报表工具 让数据分析更简单