AnCH Framework  0.1
Another C++ Hack Framework
All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Pages
observable.hpp
1 /*
2  ANCH Framework: ANother C++ Hack is a C++ framework based on C++11 standard
3  Copyright (C) 2012 Vincent Lachenal
4 
5  This file is part of ANCH Framework.
6 
7  ANCH Framework is free software: you can redistribute it and/or modify
8  it under the terms of the GNU Lesser 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  ANCH Framework 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 Lesser General Public License for more details.
16 
17  You should have received a copy of the GNU Lesser General Public License
18  along with ANCH Framework. If not, see <http://www.gnu.org/licenses/>.
19 */
20 #ifndef _ANCH_EVENTS_OBSERVABLE_H_
21 #define _ANCH_EVENTS_OBSERVABLE_H_
22 
23 #include <mutex>
24 #include <set>
25 
26 #include "events/observer.hpp"
27 #include "lessPtrCompare.hpp"
28 
29 
30 namespace anch {
31  namespace events {
32 
42  template<typename Event>
43  class Observable {
44 
45  private:
46  // Attributes +
48  std::set<anch::events::Observer<Event>*, anch::LessPtrCompare<Observer<Event> > > _observers;
49 
51  std::mutex _mutex;
52  // Attributes -
53 
54  public:
55  // Constructors +
59  Observable(): _observers(), _mutex() {
60  // Nothing to do
61  }
62  // Constructors -
63 
64  // Destructor +
68  virtual ~Observable() {
69  // Nothing to do
70  }
71  // Destructor -
72 
73  public:
74  // Methods +
83  _mutex.lock();
84  bool added = _observers.insert(&observer).second;
85  _mutex.unlock();
86  return added;
87  }
88 
95  _mutex.lock();
96  _observers.erase(&observer);
97  _mutex.unlock();
98  }
99 
105  void notifyObservers(const Event& event) {
106  _mutex.lock();
107  for(anch::events::Observer<Event>* observer : _observers) {
108  observer->notify(event);
109  }
110  _mutex.unlock();
111  }
112  // Methods -
113 
114  };
115 
116  }
117 }
118 
119 #endif // _ANCH_EVENTS_OBSERVABLE_H_
An observer interface of the observers/observable design pattern.
Definition: observer.hpp:39
An observable implementation of the observers/observable design pattern.
Definition: observable.hpp:43
Observable()
Definition: observable.hpp:59
void notifyObservers(const Event &event)
Definition: observable.hpp:105
AnCH framework base namespace.
Definition: base64.hpp:28
virtual ~Observable()
Definition: observable.hpp:68
Less comparator based on object address.
Definition: lessPtrCompare.hpp:35
bool addObserver(anch::events::Observer< Event > &observer)
Definition: observable.hpp:82
void removeObserver(anch::events::Observer< Event > &observer)
Definition: observable.hpp:94