BsServiceLocator.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #pragma once
  2. #include "BsPrerequisitesUtil.h"
  3. #include "BsException.h"
  4. namespace BansheeEngine
  5. {
  6. /** @addtogroup General
  7. * @{
  8. */
  9. /**
  10. * A locator system that allows you to quickly find a service of a specific type.
  11. *
  12. * @note
  13. * This is similar to a singleton pattern but unlike singleton the active instance is not required to be available and
  14. * can be replaced with another system during runtime, or completely removed.
  15. */
  16. template <class T>
  17. class ServiceLocator
  18. {
  19. public:
  20. /**
  21. * Returns an instance of the service we are looking for, if one is available.
  22. *
  23. * @note Can return null.
  24. */
  25. static T* instance() { return mService; }
  26. /** Starts providing a new service when "instance()" is called. Replaces the previous service. */
  27. static void _provide(T* service)
  28. {
  29. mService = service;
  30. }
  31. /**
  32. * Stops providing a service when "instance()" is called. Ignored if the current service doesn't match the
  33. * provided service.
  34. */
  35. static void _remove(T* service)
  36. {
  37. if (mService != service)
  38. return;
  39. mService = nullptr;
  40. }
  41. private:
  42. static T* mService;
  43. };
  44. template <class T>
  45. T* ServiceLocator<T>::mService = nullptr;
  46. /** @} */
  47. }