• 一个好用的单例类模板


    在程序开发中,某一个类对象经常需要在好多个类中使用,为测试方便,好多初学者声明一个该类的全局变量,然后在其它类中引用使用。

    但是,好的编码是能不用全局变量就不用全局变量。

    这些类对象往往时单一的对象,于是可以使用设计模式中的单例模式来很好地规避全局变量的使用。

     Singleton.h
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
     
    #ifndef SINGLETON_H
    #define SINGLETON_H

    #include <QMutex>

    template<typename T, typename L = QMutex>
    class Singleton
    {
    public:
        
    template<typename ...Args>
        
    static T *getSingleton(Args&&... args)
        {
            
    if (!m_init)
            {
                
    if (nullptr == m_inst)
                {
                    m_lock.lock();
                    m_init = 
    new T(std::forward<Args>(args)...);
                    m_init = 
    true;
                    m_lock.unlock();
                }
            }
            
    return m_inst;
        }

    private:
        Singleton() {}

    private:
        
    static bool m_init;
        
    static T    *m_inst;
        
    static L    m_lock;
    };

    template<typename T, typename L>
    bool Singleton<T, L>::m_init = false;

    template<typename T, typename L>
    T *Singleton<T, L>::m_inst = nullptr;

    template<typename T, typename L>
    L Singleton<T, L>::m_lock;

    #endif // SINGLETON_H

    使用:

    您的类名 *对象指针名 = Singleton<您的类名>::getSingleton([构造函数参数列表,可选]);

     C++ Code 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
     
    class WindowService
    {
    public:
        WindowService(
    const QString &name) { m_name = name; }
        ~WindowService() {}

    private:
        QString     m_name;
    };

    WindowService *winSvr = Singleton<WindowService>::getSingleton(
    "WindowService");

    祝您使用愉快!

  • 相关阅读:
    jmeter----Linux上安装与使用
    Jmeter----客户端内存配置修改(Windows)
    Jmeter----生成HTML性能测试报告(Windows)
    nginx
    夜神模拟器 该网站的安全证书有问题 转载:https://bbs.yeshen.com/forum.php?mod=viewthread&tid=8864
    redis慢日志
    Nginx 转载:https://blog.csdn.net/yujing1314/article/details/107000737
    top 转载:https://mp.weixin.qq.com/s/kEY1U-CGIqQ2mKbr1aG8mA
    高可用
    shell 脚本 转载:https://mp.weixin.qq.com/s/rTsLIb2p-AE3oDPQXMQmLw
  • 原文地址:https://www.cnblogs.com/MakeView660/p/11639894.html
Copyright © 2020-2023  润新知