#ifndef SINGLETON_H
#define SINGLETON_H

#include <QString>
#include <QMutex>
#include <QCoreApplication>

/**
 * 如果T的构造函数为私有，需要在T的类声明内部将 Singleton<T> 设为友元类
 */
template <class T>
class Singleton
{
private:

   static T *     m_pSingleton;        //!< Singleton -> only 1 instance allowed
   static QMutex  m_oMutexSingleton;   //!< Mutex -> 'Singleton' is thread-safe

protected:

   Singleton() {  }
   virtual ~Singleton() { }

public:

   static T * getSingleton();
   static void deleteSingleton();

protected:

   static bool isSingletonNull() { return (m_pSingleton == NULL); }

//   void deleteInstance() { Singleton<T>::deleteSingleton(); }

};

template <class T> T * Singleton<T>::m_pSingleton = NULL;
template <class T> QMutex Singleton<T>::m_oMutexSingleton;

template <class T>
T * Singleton<T>::getSingleton()
{
   if (m_pSingleton)
      return m_pSingleton;

   QMutexLocker locker(QCoreApplication::instance() ? (& m_oMutexSingleton) : NULL);
   if (! m_pSingleton) { m_pSingleton = new T(); }

   return m_pSingleton;
}

template <class T>
void Singleton<T>::deleteSingleton()
{
   QMutexLocker locker(QCoreApplication::instance() ? (& m_oMutexSingleton) : NULL);
   if (! m_pSingleton) { return; }

   delete m_pSingleton;
   m_pSingleton = NULL;
}

#endif // SINGLETON_H
