C++ 单例模式

C++ 单例模式跟Java中的单例模式没什么区别

什么是单例?

单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例

什么时候使用单例

1个类里面的方法要在很多地方都使用到的时候建议使用单例。

单例的3个步骤,也是判断是否是单例的依据

1 就是创建1个静态的类

2 私有化构造方法

3 获取唯一的对应

demo练习

创建1个fun1.h文件,内容如下

复制代码
class Singleton{
    private:
        Singleton();
        static Singleton* mInstance;
    public:
        ~Singleton();
        static Singleton* getInstance();
        void init();   
};

创建1个fun1.cpp文件内容如下

复制代码
#include <iostream>
#include <string>
#include "fun1.h"
using namespace std;
// 创建1个静态的类
Singleton* Singleton::mInstance =NULL;
// 私有化构造方法
Singleton::Singleton()
{

}
// 析构函数销毁的时候用到
Singleton::~Singleton(){

}
// 获取唯一的对象
Singleton* Singleton::getInstance(){
    if (mInstance ==NULL)
    {
        mInstance == new Singleton();
    }
    return mInstance;
    
}
// 类Singletion下的一个方法
void Singleton::init(){
      cout<<"单例模式"<<endl;
}

int main()
{
    Singleton* singletion =Singleton::getInstance();
    singletion->init();
//  或者
//  Singleton::getInstance()->init();
    return 0;
}
相关推荐
卷无止境2 天前
C++ 的Eigen 库全解析
c++
卷无止境2 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴2 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
博客18004 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴4 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨4 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
clint4569 天前
C++进阶(1)——前景提要
c++
夜悊9 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴9 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0019 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp