| 20 | /// Especially it helps doing thread-safe lazy repository-creation. |
| 21 | template <class ItemRepositoryType, bool unloadingEnabled = true, bool lazy = true> |
| 22 | struct RepositoryManager |
| 23 | { |
| 24 | public: |
| 25 | using Mutex = std::decay_t<decltype(*std::declval<ItemRepositoryType>().mutex())>; |
| 26 | explicit RepositoryManager(const QString& name, Mutex* mutex, int version = 1, |
| 27 | ItemRepositoryRegistry& registry = globalItemRepositoryRegistry()) |
| 28 | : m_name(name) |
| 29 | , m_version(version) |
| 30 | , m_registry(registry) |
| 31 | , m_mutex(mutex) |
| 32 | { |
| 33 | if (!lazy) { |
| 34 | createRepository(); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | Q_DISABLE_COPY(RepositoryManager) |
| 39 | |
| 40 | ItemRepositoryType * repository() const |
| 41 | { |
| 42 | if (!m_repository) { |
| 43 | createRepository(); |
| 44 | } |
| 45 | |
| 46 | return static_cast<ItemRepositoryType*>(m_repository); |
| 47 | } |
| 48 | |
| 49 | inline ItemRepositoryType* operator->() const |
| 50 | { |
| 51 | return repository(); |
| 52 | } |
| 53 | |
| 54 | private: |
| 55 | void createRepository() const |
| 56 | { |
| 57 | if (!m_repository) { |
| 58 | QMutexLocker lock(&m_registry.mutex()); |
| 59 | if (!m_repository) { |
| 60 | m_repository = new ItemRepositoryType(m_name, m_mutex, &m_registry, m_version); |
| 61 | (*this)->setUnloadingEnabled(unloadingEnabled); |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | QString m_name; |
| 67 | int m_version; |
| 68 | ItemRepositoryRegistry& m_registry; |
| 69 | Mutex* m_mutex; |
| 70 | mutable AbstractItemRepository* m_repository = nullptr; |
| 71 | }; |
| 72 | } |
| 73 | |
| 74 | #endif // REPOSITORYMANAGER_H |