Observer.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef mozilla_Observer_h
  6. #define mozilla_Observer_h
  7. #include "nsTObserverArray.h"
  8. namespace mozilla {
  9. /**
  10. * Observer<T> provides a way for a class to observe something.
  11. * When an event has to be broadcasted to all Observer<T>, Notify() method
  12. * is called.
  13. * T represents the type of the object passed in argument to Notify().
  14. *
  15. * @see ObserverList.
  16. */
  17. template<class T>
  18. class Observer
  19. {
  20. public:
  21. virtual ~Observer() {}
  22. virtual void Notify(const T& aParam) = 0;
  23. };
  24. /**
  25. * ObserverList<T> tracks Observer<T> and can notify them when Broadcast() is
  26. * called.
  27. * T represents the type of the object passed in argument to Broadcast() and
  28. * sent to Observer<T> objects through Notify().
  29. *
  30. * @see Observer.
  31. */
  32. template<class T>
  33. class ObserverList
  34. {
  35. public:
  36. /**
  37. * Note: When calling AddObserver, it's up to the caller to make sure the
  38. * object isn't going to be release as long as RemoveObserver hasn't been
  39. * called.
  40. *
  41. * @see RemoveObserver()
  42. */
  43. void AddObserver(Observer<T>* aObserver)
  44. {
  45. mObservers.AppendElementUnlessExists(aObserver);
  46. }
  47. /**
  48. * Remove the observer from the observer list.
  49. * @return Whether the observer has been found in the list.
  50. */
  51. bool RemoveObserver(Observer<T>* aObserver)
  52. {
  53. return mObservers.RemoveElement(aObserver);
  54. }
  55. uint32_t Length()
  56. {
  57. return mObservers.Length();
  58. }
  59. void Broadcast(const T& aParam)
  60. {
  61. typename nsTObserverArray<Observer<T>*>::ForwardIterator iter(mObservers);
  62. while (iter.HasMore()) {
  63. Observer<T>* obs = iter.GetNext();
  64. obs->Notify(aParam);
  65. }
  66. }
  67. protected:
  68. nsTObserverArray<Observer<T>*> mObservers;
  69. };
  70. } // namespace mozilla
  71. #endif // mozilla_Observer_h