设计模式singleton 模板类实现

为什么用模板, 因为项目中大量的类,只需要唯一对象,而且这些对象会被其它的类分别大量引用

看代码, 网上有好多类似代码,我mutex用了qt的


#ifndef SINGLETON_H
#define SINGLETON_H
 
  
#define __instance(cls) Singleton::getInstance()
 
  
#include "Header.h"
 
  
template <class T>
class Singleton
{
public:
    static T* getInstance();
 
  
protected:
    Singleton(){};
 
  
private:
    Singleton(const Singleton&){};//禁止拷贝
    virtual ~Singleton() {};
 
  
    Singleton& operator=(const Singleton&){};//禁止赋值
    static T* m_instance;
    static QMutex m_lock;
};
 
  
//并发
template <class T> T* Singleton<T>::getInstance()
{
    if (nullptr == m_instance)
    {
        m_lock.lock();
        if (nullptr == m_instance)
        {
            m_instance = new T();
        }
        m_lock.unlock();
    }
    return m_instance;
}
 
  
template <class T> T* Singleton<T>::m_instance = nullptr;
template <class T>  QMutex Singleton<T>::m_lock;
 
  
#endif // SINGLETON_H

如何使用呢,下面是我自己写的Err线程安全的管理器, 看下面, 顺序说一下friend 类无所谓public protected,放哪都行

是不是很简单, 用的时候,直接 __instance(ErrMgr)->getLastErr();

#ifndef ErrMgr_H
#define ErrMgr_H
 
  
#include "Header.h"
 
  
class ErrMgr : public QObject
{
    Q_OBJECT
    friend class Singleton<ErrMgr>;
 
  
public:
    void resetErr();//重置队列
    void addErr(QString str);//加入一条到队列中
    QString getLastErr();//获取最后错误
 
  
private:
    explicit ErrMgr(QObject *parent = 0);
 
  
private:
    QQueue<QString> m_arErrs;//错误信息队列
    QMutex m_mutexErrs;//多线程
    
};
 
  
#endif // ErrMgr_H
 
  



你可能感兴趣的:(设计模式singleton 模板类实现)