QT单例模式简单讲解与实现

单例模式是一种创建型设计模式,确保一个类只有一个实例,并提供一个全局访问点。在QT开发中,单例模式常用于管理全局资源,如配置管理、日志系统等。

最简单的QT单例实现

方法一:静态局部变量实现(C++11及以上推荐)

复制代码
class Singleton
{
public:
    // 获取单例实例的静态方法
    static Singleton& getInstance()
    {
        static Singleton instance;  // 线程安全的静态局部变量(C++11起)
        return instance;
    }

    // 示例方法
    void doSomething(const QString &message)
    {
        qDebug() << "Singleton is doing something"<<message;
    }

private:
    // 私有构造函数防止外部实例化
    Singleton() {}

    // 防止复制和赋值
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;
};

​​使用方式:​​

复制代码
Singleton::getInstance().doSomething("Message 1");

如果你需要多次使用同一个实例,可以这样:

复制代码
Singleton &singleton= Singleton::getInstance();
singleton.doSomething("Message 1");
singleton.doSomething("Message 2");

方法二:指针实现(兼容旧版C++)

复制代码
class Singleton
{
public:
    static Singleton* getInstance()
    {
        if (!instance) {
            instance = new Singleton();
        }
        return instance;
    }

    void doSomething()
    {
        qDebug() << "Singleton is doing something";
    }

private:
    Singleton() {}
    static Singleton* instance;
};

// 初始化静态成员变量
Singleton* Singleton::instance = nullptr;

​​注意:​​ 这种方法不是线程安全的,如果需要线程安全,需要加锁。

QT特有的单例实现(Q_GLOBAL_STATIC)

QT提供了一个宏来更方便地实现单例:

复制代码
#include <QGlobalStatic>

Q_GLOBAL_STATIC(Singleton, singletonInstance)

class Singleton
{
public:
    void doSomething()
    {
        qDebug() << "Singleton is doing something";
    }

private:
    Singleton() {}
    friend class QGlobalStatic<Singleton>;
};

​​使用方式:​​

复制代码
singletonInstance()->doSomething();

为什么使用单例模式?

  • 控制资源访问(如配置文件)
  • 避免重复创建消耗资源的对象
  • 提供全局访问点

注意事项

  • 单例模式可能使代码更难测试
  • 过度使用会导致代码耦合度高
  • 考虑线程安全问题

以上就是在QT中实现单例模式的几种常见方法,第一种方法(静态局部变量)是最简单且线程安全的实现方式,推荐使用。

相关推荐
来让爷抱一个6 小时前
Python 异步里混用同步库,事件循环被卡住的全过程
开发语言·python
Linux-lucky6 小时前
45-Linux学习之旅之防火墙与WEB加固
linux·前端·网络·学习·ubuntu
禁默6 小时前
启元 Q1 二次开发实践:Ubuntu 部署与仿真验证,从 PrimeConsole 到 ROS 2 Humble + RViz
linux·运维·ubuntu
skywalk81637 小时前
把 去也网站 从 Ubuntu 搬到 FreeBSD:一次 Service Jail + nginx 的部署实录
linux·运维·nginx·ubuntu·freebsd
心祭丫丫9 小时前
【每天一个 Python 小案例17】Python 实现通讯录
开发语言·人工智能·笔记·python·学习
露天赏雪9 小时前
第3篇:Sentinel熔断降级实战:大模型接口抖动时的服务兜底方案
java·开发语言·人工智能·spring boot·spring·servlet·sentinel
yeccheng11 小时前
MySQL 索引超详解:从底层 B+ 树到面试高频考点
java·开发语言·jvm·mysql·面试
联犀11 小时前
纯 Go 的 CAD 开源库 go-cad:直接解析 DWG/DXF,现在也能导出 PDF
开发语言·golang·pdf
zjxtxdy12 小时前
C++面向对象程序开发-类与对象
开发语言·c++
qq_4069810314 小时前
c++拷贝构造函数
开发语言·c++