-
Notifications
You must be signed in to change notification settings - Fork 23
/
example-observer-pattern.cpp
104 lines (92 loc) · 1.81 KB
/
example-observer-pattern.cpp
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
#include <iostream>
#include "ObserverPattern.h"
// A data model that other modules are interested in when its state changes
class DataModel: public Observable
{
private:
int num;
public:
DataModel(){ num = 0; }
void setNumber(int num)
{
this->num = num;
notifyObservers(); // let interested Observers know that the state changed
}
int getNumber(){ return num; }
};
// one presentation of data that always shows its current state
class Logger
{
public:
void showNumber(const int number)
{
std::cout<<"There is a new number: "<<number<<std::endl;
}
};
class Alert
{
public:
void sendAlert(const int number, const char* alert)
{
std::cout<<"ALERT! "<<number<<" is "<<alert<<std::endl;
}
};
// controller that gathers input to change data model and drives log updates
class IOController: public IObserver
{
private:
DataModel* current;
Logger output;
public:
IOController(DataModel* data)
{
current = data;
current->addObserver(this);
}
void input(int x)
{
current->setNumber(x);
}
void update()
{
output.showNumber(current->getNumber());
}
};
//controller that displays alerts under certain conditions
class AlertController: public IObserver
{
private:
DataModel* dataState;
Alert display;
public:
AlertController(DataModel* data)
{
dataState = data;
dataState->addObserver(this);
}
void update()
{
int num = dataState->getNumber();
if( num < 0 )
{
display.sendAlert(num,"negative");
}
else if( num == 0 )
{
display.sendAlert(num,"zero");
}
}
};
//Program run
int main()
{
DataModel persistant;
IOController io(&persistant);
AlertController notifications(&persistant);
// simulate the user's actions that change state
io.input(100);
io.input(10);
io.input(-1);
io.input(0);
return 0;
}