1 | #pragma once
|
---|
2 | #ifndef __GENERIC_OBSERVER_H__
|
---|
3 | #define __GENERIC_OBSERVER_H__
|
---|
4 |
|
---|
5 | #include <list>
|
---|
6 |
|
---|
7 | #include "GenericObserverInterface.h"
|
---|
8 | #include "qmutex.h"
|
---|
9 |
|
---|
10 | namespace pacpus {
|
---|
11 |
|
---|
12 | /** Base class for te GenericObservable template.
|
---|
13 |
|
---|
14 | The purpose of this class is to be able to take generic pointers on
|
---|
15 | GenericObservable class template instances.
|
---|
16 | */
|
---|
17 | class GenericObservableBase {
|
---|
18 | public:
|
---|
19 | virtual ~GenericObservableBase() {}
|
---|
20 | };
|
---|
21 |
|
---|
22 | /** GenericObservable
|
---|
23 | Base class template for observable objects (see Observable/Observer
|
---|
24 | design pattern).
|
---|
25 |
|
---|
26 | This class implements a simple subject able to notify a list of
|
---|
27 | observers through calls to the notifyObservers protected method.
|
---|
28 | */
|
---|
29 | template <typename T>
|
---|
30 | class GenericObservable : GenericObservableBase {
|
---|
31 | public:
|
---|
32 | typedef GenericObserverInterface<T> ObserverType;
|
---|
33 |
|
---|
34 | GenericObservable() {}
|
---|
35 | virtual ~GenericObservable() {}
|
---|
36 |
|
---|
37 | /** Attaches a new observer to the observable.
|
---|
38 | @param observer A reference to a class obeying the GenericObserverInterface interface.
|
---|
39 | */
|
---|
40 | void attachObserver(ObserverType& observer) {
|
---|
41 | observers_.push_back(&observer);
|
---|
42 | }
|
---|
43 |
|
---|
44 | /** Detaches an observer.
|
---|
45 |
|
---|
46 | @param observer A reference to a class obeying the GenericObserverInterface interface.
|
---|
47 | @note Does nothing if the observer has not been previously attached
|
---|
48 | */
|
---|
49 | void detachObserver(ObserverType& observer) {
|
---|
50 | observers_.remove(&observer);
|
---|
51 | }
|
---|
52 |
|
---|
53 | /** Notifies all observers about an observable event.
|
---|
54 | */
|
---|
55 | void notifyObservers() {
|
---|
56 | typename std::list<ObserverType*>::const_iterator it;
|
---|
57 | for (it = observers_.begin(); it != observers_.end(); ++it) {
|
---|
58 | (*it)->update(static_cast<T*>(this));
|
---|
59 | }
|
---|
60 | }
|
---|
61 |
|
---|
62 | private:
|
---|
63 | std::list<ObserverType*> observers_;
|
---|
64 | };
|
---|
65 |
|
---|
66 | } // namespace pacpus
|
---|
67 |
|
---|
68 | #endif
|
---|