-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObserver.cpp
More file actions
85 lines (76 loc) · 1.8 KB
/
Observer.cpp
File metadata and controls
85 lines (76 loc) · 1.8 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
//
// Created by osher on 14/02/2022.
//
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
class Observer {
public:
virtual void update(const char *course) = 0;
};
class Subject {
protected:
vector<Observer *> observers;
public:
void Attach(Observer *observer) {
observers.push_back(observer);
}
void Detach(Observer *observer) {
for (auto o : observers)
if (o == observer)
observer = nullptr;
}
virtual void Notify(const char* course) {
for (auto o : observers)
if (o != nullptr)
o->update(course);
}
};
class Moodle : public Subject {
int mathScore, algoScore;
public:
Moodle() {
mathScore = 0;
algoScore = 0;
}
void setScore(const char *course, int score) {
if (strcmp(course, "algo") == 0) {
algoScore = score;
Notify("algo");
return;
}
if (strcmp(course, "math") == 0) {
algoScore = score;
Notify("math");
}
}
int getScore(const char* course) const {
if (strcmp(course, "algo") == 0)
return algoScore;
if (strcmp(course, "math") == 0)
return mathScore;
return 0;
}
};
class Student : public Observer {
Moodle* _moodle;
public:
Student(Moodle* moodle) {
_moodle = moodle;
}
void update(const char *course) override {
if (strcmp(course, "algo") == 0) {
if(_moodle->getScore("algo") > 80)
cout << "WOW." << endl;
}
}
};
int main() {
Moodle* moodle = new Moodle();
Student* s = new Student(moodle);
moodle->Attach(s);
moodle->setScore("math", 100);
moodle->setScore("algo", 70);
moodle->setScore("algo", 81);
}