#pragma once #ifndef __GENERIC_OBSERVER_H__ #define __GENERIC_OBSERVER_H__ #include #include "GenericObserverInterface.h" #include namespace pacpus { /** Base class for te GenericObservable template. The purpose of this class is to be able to take generic pointers on GenericObservable class template instances. */ class GenericObservableBase { public: virtual ~GenericObservableBase() {} }; /** GenericObservable Base class template for observable objects (see Observable/Observer design pattern). This class implements a simple subject able to notify a list of observers through calls to the notifyObservers protected method. */ template class GenericObservable : GenericObservableBase { public: typedef GenericObserverInterface ObserverType; GenericObservable() {} virtual ~GenericObservable() {} /** Attaches a new observer to the observable. @param observer A reference to a class obeying the GenericObserverInterface interface. */ void attachObserver(ObserverType& observer) { observers_.push_back(&observer); } /** Detaches an observer. @param observer A reference to a class obeying the GenericObserverInterface interface. @note Does nothing if the observer has not been previously attached */ void detachObserver(ObserverType& observer) { observers_.remove(&observer); } /** Notifies all observers about an observable event. */ void notifyObservers() { typename std::list::const_iterator it; for (it = observers_.begin(); it != observers_.end(); ++it) { (*it)->update(static_cast(this)); } } private: std::list observers_; }; } // namespace pacpus #endif