michael@0: /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: #ifndef mozilla_Observer_h michael@0: #define mozilla_Observer_h michael@0: michael@0: #include "nsTArray.h" michael@0: michael@0: namespace mozilla { michael@0: michael@0: /** michael@0: * Observer provides a way for a class to observe something. michael@0: * When an event has to be broadcasted to all Observer, Notify() method michael@0: * is called. michael@0: * T represents the type of the object passed in argument to Notify(). michael@0: * michael@0: * @see ObserverList. michael@0: */ michael@0: template michael@0: class Observer michael@0: { michael@0: public: michael@0: virtual ~Observer() { } michael@0: virtual void Notify(const T& aParam) = 0; michael@0: }; michael@0: michael@0: /** michael@0: * ObserverList tracks Observer and can notify them when Broadcast() is michael@0: * called. michael@0: * T represents the type of the object passed in argument to Broadcast() and michael@0: * sent to Observer objects through Notify(). michael@0: * michael@0: * @see Observer. michael@0: */ michael@0: template michael@0: class ObserverList michael@0: { michael@0: public: michael@0: /** michael@0: * Note: When calling AddObserver, it's up to the caller to make sure the michael@0: * object isn't going to be release as long as RemoveObserver hasn't been michael@0: * called. michael@0: * michael@0: * @see RemoveObserver() michael@0: */ michael@0: void AddObserver(Observer* aObserver) { michael@0: mObservers.AppendElement(aObserver); michael@0: } michael@0: michael@0: /** michael@0: * Remove the observer from the observer list. michael@0: * @return Whether the observer has been found in the list. michael@0: */ michael@0: bool RemoveObserver(Observer* aObserver) { michael@0: return mObservers.RemoveElement(aObserver); michael@0: } michael@0: michael@0: uint32_t Length() { michael@0: return mObservers.Length(); michael@0: } michael@0: michael@0: void Broadcast(const T& aParam) { michael@0: uint32_t size = mObservers.Length(); michael@0: for (uint32_t i=0; iNotify(aParam); michael@0: } michael@0: } michael@0: michael@0: protected: michael@0: nsTArray*> mObservers; michael@0: }; michael@0: michael@0: } // namespace mozilla michael@0: michael@0: #endif // mozilla_Observer_h