Created
February 18, 2014 09:17
-
-
Save PoisonousJohn/9067379 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <unordered_map> | |
#include <string> | |
#include <assert.h> | |
using namespace std; | |
class ServiceInterface { | |
public: | |
virtual ~ServiceInterface() {} | |
}; | |
class ServiceContainer | |
{ | |
private: | |
static ServiceContainer container; | |
std::unordered_map <std::string, ServiceInterface* > services_; | |
ServiceContainer(); | |
~ServiceContainer(); | |
// forbid copy | |
ServiceContainer(const ServiceContainer&); | |
ServiceContainer& operator=(const ServiceContainer&); | |
public: | |
template <typename T, typename ... Args> | |
void registerService( Args ... args ) { | |
services_.insert( std::make_pair( T::getId(), new T(args...) )); | |
} | |
void clear(); | |
template <typename T> | |
T* getService() { | |
assert(services_.find(T::getId()) != services_.end() && "sevice not found"); | |
return static_cast<T*>(services_[T::getId()]); | |
} | |
static ServiceContainer& sharedContainer(); | |
}; | |
template <typename T> | |
class Service : public ServiceInterface | |
{ | |
public: | |
Service() {} | |
T* instance() { | |
return ServiceContainer::sharedContainer().getService<T>(); | |
} | |
}; | |
int main() { | |
// your code goes here | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment