A simple implementation of the service locator design pattern in C++.
Register an instance:
ServiceLocator locator;
locator.registerInstance<IMathService>(new MathService());And resolve it somewhere else:
auto svc1 = locator.resolve<IMathService>();
auto svc2 = locator.resolve<IMathService>(); // <= same instanceRegister a delegate which creates a shared pointer to the corresponding instance:
ServiceLocator locator;
locator.registerCreator<IMathService>([]() { return std::make_shared<MathService>(); });Everytime you call resolve, the service locator will call the delegate and return the pointer:
auto svc1 = locator.resolve<IMathService>();
auto svc2 = locator.resolve<IMathService>(); // <= not the same instanceYou can clear all registrations manually (will be called in destructor automatically):
locator.clear();You can redistribute it and/or modify it under the terms of the MIT license. See LICENSE for details.