1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/xpcom/glue/Observer.h Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,77 @@ 1.4 +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ 1.5 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.6 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.7 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.8 + 1.9 +#ifndef mozilla_Observer_h 1.10 +#define mozilla_Observer_h 1.11 + 1.12 +#include "nsTArray.h" 1.13 + 1.14 +namespace mozilla { 1.15 + 1.16 +/** 1.17 + * Observer<T> provides a way for a class to observe something. 1.18 + * When an event has to be broadcasted to all Observer<T>, Notify() method 1.19 + * is called. 1.20 + * T represents the type of the object passed in argument to Notify(). 1.21 + * 1.22 + * @see ObserverList. 1.23 + */ 1.24 +template <class T> 1.25 +class Observer 1.26 +{ 1.27 +public: 1.28 + virtual ~Observer() { } 1.29 + virtual void Notify(const T& aParam) = 0; 1.30 +}; 1.31 + 1.32 +/** 1.33 + * ObserverList<T> tracks Observer<T> and can notify them when Broadcast() is 1.34 + * called. 1.35 + * T represents the type of the object passed in argument to Broadcast() and 1.36 + * sent to Observer<T> objects through Notify(). 1.37 + * 1.38 + * @see Observer. 1.39 + */ 1.40 +template <class T> 1.41 +class ObserverList 1.42 +{ 1.43 +public: 1.44 + /** 1.45 + * Note: When calling AddObserver, it's up to the caller to make sure the 1.46 + * object isn't going to be release as long as RemoveObserver hasn't been 1.47 + * called. 1.48 + * 1.49 + * @see RemoveObserver() 1.50 + */ 1.51 + void AddObserver(Observer<T>* aObserver) { 1.52 + mObservers.AppendElement(aObserver); 1.53 + } 1.54 + 1.55 + /** 1.56 + * Remove the observer from the observer list. 1.57 + * @return Whether the observer has been found in the list. 1.58 + */ 1.59 + bool RemoveObserver(Observer<T>* aObserver) { 1.60 + return mObservers.RemoveElement(aObserver); 1.61 + } 1.62 + 1.63 + uint32_t Length() { 1.64 + return mObservers.Length(); 1.65 + } 1.66 + 1.67 + void Broadcast(const T& aParam) { 1.68 + uint32_t size = mObservers.Length(); 1.69 + for (uint32_t i=0; i<size; ++i) { 1.70 + mObservers[i]->Notify(aParam); 1.71 + } 1.72 + } 1.73 + 1.74 +protected: 1.75 + nsTArray<Observer<T>*> mObservers; 1.76 +}; 1.77 + 1.78 +} // namespace mozilla 1.79 + 1.80 +#endif // mozilla_Observer_h