Open Model Railroad Network (OpenMRN)
Loading...
Searching...
No Matches
ServiceLocator.hxx
Go to the documentation of this file.
1
35#ifndef _UTILS_SERVICELOCATOR_HXX_
36#define _UTILS_SERVICELOCATOR_HXX_
37
38#include <map>
39#include <memory>
40#include <string>
41#include "utils/Atomic.hxx"
42
43using std::shared_ptr;
44using std::string;
45
51template <typename ServiceType>
53{
54private:
58 static string get_type_name(const char *alias)
59 {
60 string name(__PRETTY_FUNCTION__);
61 if (alias != nullptr)
62 {
63 name += "_";
64 name += alias;
65 }
66
67 return name;
68 }
69
70 template<typename LocatorType> friend class ServiceLocator;
71};
72
77{
78public:
83 static void clear()
84 {
85 ServiceLocatorImpl::services.clear();
86 }
87
88private:
89 static std::map<string, shared_ptr<void>> services;
90 static Atomic lock_;
91
98 static void register_service(string name, shared_ptr<void> &service)
99 {
100 AtomicHolder l(&ServiceLocatorImpl::lock_);
101 ServiceLocatorImpl::services[name] = service;
102 }
103
110 static shared_ptr<void> get_service(string name)
111 {
112 AtomicHolder l(&ServiceLocatorImpl::lock_);
113 auto it = ServiceLocatorImpl::services.find(name);
114 if (it == ServiceLocatorImpl::services.end())
115 {
116 return nullptr;
117 }
118
119 return it->second;
120 }
121
122 template<typename ServiceType> friend class ServiceLocator;
123};
124
125template <typename ServiceType>
127{
128public:
134 static shared_ptr<ServiceType> get_service(const char *alias = nullptr)
135 {
137 shared_ptr<void> service = ServiceLocatorImpl::get_service(name);
138 return std::static_pointer_cast<ServiceType>(service);
139 }
140
147 static void register_service(
148 shared_ptr<ServiceType> &service, const char *alias = nullptr)
149 {
151 shared_ptr<void> temp(service);
153 }
154};
155
156#endif // _UTILS_SERVICELOCATOR_HXX_
157
See OSMutexLock in os/OS.hxx.
Definition Atomic.hxx:153
Lightweight locking class for protecting small critical sections.
Definition Atomic.hxx:130
The sole purpose of this templated class is to provide access to a string that is specific to a type.
static string get_type_name(const char *alias)
Get a name that has the derived type as part of the name.
Provides the shared storage for registrations.
static void register_service(string name, shared_ptr< void > &service)
Register a pointer with a name.
static void clear()
Remove all of the registerations for all types.
static shared_ptr< void > get_service(string name)
Retrieves a pointer to the registered service, by name.
static shared_ptr< ServiceType > get_service(const char *alias=nullptr)
Get the service that has been registereed for this type.
static void register_service(shared_ptr< ServiceType > &service, const char *alias=nullptr)
Register a service instance with the service locator.