BsServiceLocator.h 1.2 KB

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