forked from kbuffardi/ObserverPattern-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample-observer-pattern.cpp
More file actions
78 lines (71 loc) · 1.16 KB
/
example-observer-pattern.cpp
File metadata and controls
78 lines (71 loc) · 1.16 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
#include <iostream>
#include "ObserverPattern.cpp"
///////////////////EXAMPLE USAGE IN SIMPLISTIC PSEUDO-MVC ARCHITECTURE:
class AnInt: public Observable
{
private:
int num;
public:
AnInt(){ num = 0; }
void setInfo(int num)
{
this->num = num;
notifyObservers();
}
int getNum(){ return num; }
};
class NumWatcherView
{
public:
void showNum(int num) //interface override
{
std::cout<<"There is a new number: "<<num<<std::endl;
}
};
class AlertView
{
private:
bool isNegative(int num)
{
return num < 0;
}
public:
void checkAlerts(int num)
{
if(isNegative(num))
{
std::cout<<"ALERT! "<<num<<" is negative!"<<std::endl;
}
}
};
class NumberController: public IObserver
{
private:
AnInt current;
AlertView alerts;
NumWatcherView output;
public:
NumberController()
{
current.addObserver(this);
}
void set(int x)
{
current.setInfo(x);
}
void update()
{
output.showNum(current.getNum());
alerts.checkAlerts(current.getNum());
}
};
//the user's actions
int main()
{
NumberController example;
example.set(100);
example.set(10);
example.set(-1);
example.set(0);
return 0;
}