Skip to content

Instantly share code, notes, and snippets.

@PoisonousJohn
Created February 18, 2014 09:17
Show Gist options
  • Save PoisonousJohn/9067379 to your computer and use it in GitHub Desktop.
Save PoisonousJohn/9067379 to your computer and use it in GitHub Desktop.
#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