BsServiceLocator.h 1.5 KB

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