-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobserver_pattern.cpp
More file actions
111 lines (90 loc) · 2.05 KB
/
observer_pattern.cpp
File metadata and controls
111 lines (90 loc) · 2.05 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/****
* Simple observer pattern.
* Short story:
* A key notifier in a TV software notifies possible menus
* on the TV software when a button is pressed on the remote controller.
* Accoring to their states, menus take necessary actions.
* */
#include <iostream>
#include <vector>
/// State of Menus/OSDs
static const int OFF = 0;
static const int ON = 1;
//Remote Controller Keys
static const int KEY_MAIN_MENU = 1;
static const int KEY_EXIT = 0;
/// Observer Interface
class Observer
{
public:
virtual void update(int key) = 0;
};
/// Subject Interface
class Subject
{
public:
virtual void registerObserver(Observer *o) = 0;
// virtual void removeObserver(Observer *o) = 0;
virtual void notifyObservers() = 0;
};
class KeyNotifier : public Subject
{
int _key;
std::vector<Observer*> _menuList;
public:
void registerObserver(Observer* o){
_menuList.push_back(o);
}
void notifyObservers(){
for(const auto &menu : _menuList){
menu->update(_key);
}
}
void setKey(int key){
_key = key;
//Notify all observers!
notifyObservers();
}
};
class MainMenu : public Observer{
int _state;
public:
MainMenu(KeyNotifier* pKeyNotifier, int state) : _state(state){
/// Register observer to subject
pKeyNotifier->registerObserver(this);
}
void update(int key){
if(_state == OFF && key == KEY_MAIN_MENU){
std::cout << "Main Menu is opened" << std::endl;
_state = ON;
}
else{
std::cout << "Main menu, do nothing!" << std::endl;
}
}
};
class IdleMenu: public Observer{
int _state;
public:
IdleMenu(KeyNotifier* pKeyNotifier, int state) : _state(state){
//Attach idle menu to key notifier.
pKeyNotifier->registerObserver(this);
}
void update(int key){
if(_state == OFF && key == KEY_MAIN_MENU){
std::cout << "Main Menu is closed" << std::endl;
_state = ON;
}
else{
std::cout << "Idle menu, do nothing!" << std::endl;
}
}
};
int main(){
/// TV is starting...
KeyNotifier kn;
MainMenu mm(&kn, OFF);
IdleMenu im(&kn, OFF); ///No menu at all, it's video screen.
//Press Main Menu button
kn.setKey(KEY_MAIN_MENU);
}