-
Notifications
You must be signed in to change notification settings - Fork 0
/
Observer.h
48 lines (42 loc) · 809 Bytes
/
Observer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#pragma once
#include <vector>
#include <algorithm>
/*
Observer - Abstract class
update method needs to be implemented by observers
*/
class Observer
{
public:
virtual void update() = 0;
virtual ~Observer() {}
};
/*
Observable or Subject - class that notifies changes in its state
Derive from this class if you want to provide notifications
*/
class Observable
{
private:
//Non-owning pointers to observer instances
std::vector<Observer*> observers;
public:
virtual ~Observable() {}
void addObserver(Observer *obs)
{
observers.push_back(obs);
}
void removeObserver(Observer *obs)
{
auto it = std::find(observers.begin(), observers.end(), obs);
if (it != observers.end())
observers.erase(it);
}
void notify()
{
for (auto obs: observers)
{
obs->update();
}
}
};