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中实现单例模式的几种常见方法,第一种方法(静态局部变量)是最简单且线程安全的实现方式,推荐使用。

相关推荐
郑州光合科技余经理4 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1234 天前
matlab画图工具
开发语言·matlab
dustcell.4 天前
haproxy七层代理
java·开发语言·前端
norlan_jame4 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone4 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
欧云服务器4 天前
怎么让脚本命令可以同时在centos、debian、ubuntu执行?
ubuntu·centos·debian
QQ4022054964 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月4 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
智渊AI4 天前
Ubuntu 20.04/22.04 下通过 NVM 安装 Node.js 22(LTS 稳定版)
ubuntu·node.js·vim
m0_531237174 天前
C语言-数组练习进阶
c语言·开发语言·算法