-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchainresp_01.cpp
More file actions
47 lines (42 loc) · 1.32 KB
/
chainresp_01.cpp
File metadata and controls
47 lines (42 loc) · 1.32 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
#include <iostream>
using namespace std;
class Message {
protected:
int myId;
public:
operator int() { return myId; }
Message(int id) : myId(id) {}
/*
equalTo - the Message Obect determines its equality with another message object. This may well be an == operator
*/
virtual bool equalTo(int id) {
return id % myId == 0;
}
};
class HandlerBase {
Message myMessage;
protected:
HandlerBase *m_successor;
public:
HandlerBase(HandlerBase *s, Message *m) : m_successor(s), myMessage(*m) {}
virtual void HandleMessage(Message *m) {
if(myMessage.equalTo(*m)) { // test equality with own message and handle it
cout << "Message " << *m << " got handled by " << myMessage << "\n";
} else if(m_successor) { // else hand over to next handler in line
cout << "Message " << *m << " got handed to successor" << "\n";
m_successor->HandleMessage(m);
} else { // or if this was the last handler, give up
cout << "Message " << *m << " had no handler" << "\n";
}
}
};
int main() {
Message m1(3), m2(5), m3(7), m4(4);
HandlerBase h1(0, &m1), h2(&h1,&m2), h3(&h2,&m3), h4(&h3,&m4); // create handler chain h4 <> h3 <> h2 <> h1
int m;
while(cin >> m) {
Message newMsg(m);
h4.HandleMessage(&newMsg);
}
return 0;
}