/** * * Distributed under the UTC Heudiascy Pacpus License, Version 1.0. * Copyright (c) UTC Heudiasyc 2010 - 2013. All rights reserved. * * See the LICENSE file for more information or a copy at: * http://www.hds.utc.fr/~kurdejma/LICENSE_1_0.txt * */ #ifndef DEF_PACPUS_GENERIC_OBSERVER_H #define DEF_PACPUS_GENERIC_OBSERVER_H #include #include #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 // DEF_PACPUS_GENERIC_OBSERVER_H