Open-Typer
Open source typewriting tutor program
Loading...
Searching...
No Matches
ModulesIoC.h
1/*
2 * ModulesIoC.h
3 * This file is part of Open-Typer
4 *
5 * Copyright (C) 2023 - adazem009
6 *
7 * Open-Typer is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * Open-Typer is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with Open-Typer. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21#ifndef MODULESIOC_H
22#define MODULESIOC_H
23
24#include <QString>
25#include <map>
26#include <memory>
27#include "IModuleExportInterface.h"
28
30{
31 public:
32 static void init()
33 {
34 m_initialized = true;
35 }
36
37 static ModulesIoC *instance()
38 {
39 if(!m_initialized)
40 {
41 if(m_initialized == false)
42 Q_ASSERT(false);
43 return nullptr;
44 }
45 static ModulesIoC instance;
46 if(instance.m_customInstance)
47 return instance.m_customInstance;
48 else
49 return &instance;
50 }
51
52 static void setCustomInstance(ModulesIoC *i)
53 {
54 Q_ASSERT(i);
55 init();
56 instance()->m_customInstance = i;
57 }
58
59 template <class I>
60 void registerExport(std::shared_ptr<I> instance)
61 {
62 QString id = typeid(I).name();
63 auto it = m_map.find(id);
64 if(it != m_map.end())
65 Q_ASSERT(false);
66 auto sharedInstance = std::shared_ptr<I>(instance);
67 auto interface = std::dynamic_pointer_cast<IModuleExportInterface>(sharedInstance);
68 if(!interface)
69 {
70 Q_ASSERT(interface);
71 return;
72 }
73 m_map[id] = { interface };
74 }
75
76 std::shared_ptr<IModuleExportInterface> doResolvePtrById(const QString &id)
77 {
78 auto it = m_map.find(id);
79 if(it == m_map.end())
80 {
81 Q_ASSERT(false);
82 return nullptr;
83 }
84
85 Service &service = it->second;
86 if(service.p)
87 return service.p;
88
89 return nullptr;
90 }
91
92 template <class I>
93 std::shared_ptr<I> resolve()
94 {
95 QString id = typeid(I).name();
96 std::shared_ptr<IModuleExportInterface> service = doResolvePtrById(id);
97 return std::static_pointer_cast<I>(service);
98 }
99
100 private:
101 struct Service
102 {
103 std::shared_ptr<IModuleExportInterface> p;
104 };
105
106 std::map<QString, Service> m_map;
107 ModulesIoC *m_customInstance = nullptr;
108 inline static bool m_initialized = false;
109};
110
111#endif // MODULESIOC_H
Definition IModuleExportInterface.h:29
Definition ModulesIoC.h:30
Definition ModulesIoC.h:102