C++ 单例模式三种写法
#include <iostream> #include "Apple.h" #include "Singleton.h" #include "ActivityManager.h" #include "ResourceManager.h" using namespace MySpace; int main() { Apple::abc = 10; //参考:https://blog.csdn.net/unonoi/article/details/121138176 // /* * 单例模式可以分为 懒汉式 和 饿汉式 ,两者之间的区别在于创建实例的时间不同。 懒汉式 系统运行中,实例并不存在,只有当需要使用该实例时,才会去创建并使用实例。这种方式要考虑线程安全。 饿汉式 系统一运行,就初始化创建实例,当需要时,直接调用即可。这种方式本身就线程安全,没有多线程的线程安全问题。 */ //方法一: 饿汉式单例(本身就线程安全), 在系统启动时就创建好了 Apple& app = Apple::Instance(); app.SayHello(); //用宏方便写 gApple.SayHello(); //方法二: MySpace::ResourceManager::Instance().SayHello(); //方法三: 使用一个单例宏 MySpace::Singleton<ActivityManager>::instance().SayHello(); ACTIVITY_MANAGER.SayHello(); system("pause"); }
Apple.h
#pragma once #include <iostream> class Apple { public: static Apple& Instance() { return s_kInstance; } static int abc; public: inline void SayHello() { std::cout << "Apple Hello" << std::endl; } private: //Apple(); 没写, 这样CPP就不用写了 //~Apple(); Apple() { std::cout << "Apple Constructor" << std::endl; } static Apple s_kInstance; }; #define gApple (Apple::Instance())
Apple.cpp
#include "Apple.h" Apple Apple::s_kInstance; int Apple::abc = 5;
ResourceManager.h
#pragma once #include <iostream> namespace MySpace { class ResourceManager { public: static ResourceManager& Instance(); void SayHello(); ResourceManager() { std::cout << "ResourceManager Constructor" << std::endl; } }; }
ResourceManager.cpp
#include "ResourceManager.h" using namespace MySpace; ResourceManager& ResourceManager::Instance() { static ResourceManager resMgr; return resMgr; } void ResourceManager::SayHello() { std::cout << "ResourceManager Hello" << std::endl; }
Singleton.h
#pragma once namespace MySpace { template<typename T> class Singleton { public: static T& instance() { static T t; return t; } private: Singleton(); ~Singleton(); Singleton(const Singleton&); Singleton& operator=(const Singleton&); }; }
ActivityManager.h
#pragma once #include <iostream> namespace MySpace { class ActivityManager { public: void SayHello(); ActivityManager() { std::cout << "ActivityManager Constructor" << std::endl; } }; #define ACTIVITY_MANAGER MySpace::Singleton<ActivityManager>::instance() }
ActivityManager.cpp
#include "ActivityManager.h" using namespace MySpace; void ActivityManager::SayHello() { std::cout << "ActivityManager Hello" << std::endl; }
分类:
C++
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
2013-07-25 MFC学习 文件操作注册表操作