ScummVM API documentation
observable.h
1/* ScummVM - Graphic Adventure Engine
2 *
3 * ScummVM is the legal property of its developers, whose names
4 * are too numerous to list here. Please refer to the COPYRIGHT
5 * file distributed with this source distribution.
6 *
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 *
20 */
21
22#ifndef ULTIMA4_CORE_OBSERVABLE_H
23#define ULTIMA4_CORE_OBSERVABLE_H
24
25#include "ultima/ultima4/core/observer.h"
26#include "common/array.h"
27
28namespace Ultima {
29namespace Ultima4 {
30
44template <class O, class A = NoArg *>
46public:
47 Observable() : _changed(false) {}
48
49 void addObserver(Observer<O, A> *o) {
50 typename Common::Array< Observer<O, A> *>::iterator i;
51 i = Common::find(_observers.begin(), _observers.end(), o);
52 if (i == _observers.end())
53 _observers.push_back(o);
54 }
55
56 int countObservers() const {
57 return _observers.size();
58 }
59
60 void deleteObserver(Observer<O, A> *o) {
61 typename Common::Array< Observer<O, A> *>::iterator i;
62 i = Common::find(_observers.begin(), _observers.end(), o);
63 if (i != _observers.end())
64 _observers.erase(i);
65 }
66
67 void deleteObservers() {
68 _observers.clear();
69 }
70
71 bool hasChanged() const {
72 return _changed;
73 }
74
75 void notifyObservers(A arg) {
76 if (!_changed)
77 return;
78
79 // vector iterators are invalidated if erase is called, so a copy
80 // is used to prevent problems if the observer removes itself (or
81 // otherwise changes the observer list)
82 typename Common::Array< Observer<O, A> *> tmp = _observers;
83
84 clearChanged();
85
86 for (auto *observer : tmp) {
87 observer->update(static_cast<O>(this), arg);
88 }
89 }
90
91protected:
92 void clearChanged() {
93 _changed = false;
94 }
95 void setChanged() {
96 _changed = true;
97 }
98
99private:
100 bool _changed;
101 Common::Array< Observer<O, A> *> _observers;
102};
103
104} // End of namespace Ultima4
105} // End of namespace Ultima
106
107#endif
Definition: array.h:52
Definition: observable.h:45
Definition: observer.h:37
In find(In first, In last, const T &v)
Definition: algorithm.h:225