FluentUI/example/src/singleton.h

41 lines
948 B
C
Raw Normal View History

2023-09-17 20:36:33 +08:00
#ifndef SINGLETON_H
#define SINGLETON_H
#include <QMutex>
template <typename T>
class Singleton {
public:
static T* getInstance();
private:
2024-01-04 14:28:51 +08:00
Q_DISABLE_COPY_MOVE(Singleton)
2023-09-17 20:36:33 +08:00
};
template <typename T>
T* Singleton<T>::getInstance() {
2024-01-04 14:28:51 +08:00
static QMutex mutex;
QMutexLocker locker(&mutex);
static T* instance = nullptr;
2023-09-17 20:36:33 +08:00
if (instance == nullptr) {
2024-01-04 14:28:51 +08:00
instance = new T();
2023-09-17 20:36:33 +08:00
}
return instance;
}
2024-01-04 14:28:51 +08:00
#define SINGLETON(Class) \
private: \
2023-09-17 20:36:33 +08:00
friend class Singleton<Class>; \
2024-01-04 14:28:51 +08:00
public: \
static Class* getInstance() { \
2023-09-17 20:36:33 +08:00
return Singleton<Class>::getInstance(); \
}
2023-12-30 20:33:33 +08:00
#define HIDE_CONSTRUCTOR(Class) \
private: \
Class() = default; \
Class(const Class& other) = delete; \
2024-01-04 14:28:51 +08:00
Q_DISABLE_COPY_MOVE(Class);
2023-12-30 20:33:33 +08:00
2023-09-17 20:36:33 +08:00
#endif // SINGLETON_H