|
1 /* -*- Mode: C++; tab-width: 2; 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 |
|
6 #ifndef mozilla_Observer_h |
|
7 #define mozilla_Observer_h |
|
8 |
|
9 #include "nsTArray.h" |
|
10 |
|
11 namespace mozilla { |
|
12 |
|
13 /** |
|
14 * Observer<T> provides a way for a class to observe something. |
|
15 * When an event has to be broadcasted to all Observer<T>, Notify() method |
|
16 * is called. |
|
17 * T represents the type of the object passed in argument to Notify(). |
|
18 * |
|
19 * @see ObserverList. |
|
20 */ |
|
21 template <class T> |
|
22 class Observer |
|
23 { |
|
24 public: |
|
25 virtual ~Observer() { } |
|
26 virtual void Notify(const T& aParam) = 0; |
|
27 }; |
|
28 |
|
29 /** |
|
30 * ObserverList<T> tracks Observer<T> and can notify them when Broadcast() is |
|
31 * called. |
|
32 * T represents the type of the object passed in argument to Broadcast() and |
|
33 * sent to Observer<T> objects through Notify(). |
|
34 * |
|
35 * @see Observer. |
|
36 */ |
|
37 template <class T> |
|
38 class ObserverList |
|
39 { |
|
40 public: |
|
41 /** |
|
42 * Note: When calling AddObserver, it's up to the caller to make sure the |
|
43 * object isn't going to be release as long as RemoveObserver hasn't been |
|
44 * called. |
|
45 * |
|
46 * @see RemoveObserver() |
|
47 */ |
|
48 void AddObserver(Observer<T>* aObserver) { |
|
49 mObservers.AppendElement(aObserver); |
|
50 } |
|
51 |
|
52 /** |
|
53 * Remove the observer from the observer list. |
|
54 * @return Whether the observer has been found in the list. |
|
55 */ |
|
56 bool RemoveObserver(Observer<T>* aObserver) { |
|
57 return mObservers.RemoveElement(aObserver); |
|
58 } |
|
59 |
|
60 uint32_t Length() { |
|
61 return mObservers.Length(); |
|
62 } |
|
63 |
|
64 void Broadcast(const T& aParam) { |
|
65 uint32_t size = mObservers.Length(); |
|
66 for (uint32_t i=0; i<size; ++i) { |
|
67 mObservers[i]->Notify(aParam); |
|
68 } |
|
69 } |
|
70 |
|
71 protected: |
|
72 nsTArray<Observer<T>*> mObservers; |
|
73 }; |
|
74 |
|
75 } // namespace mozilla |
|
76 |
|
77 #endif // mozilla_Observer_h |