观察者模式

观察者模式定义了一种一对多的依赖关系,多个对象订阅同一个对象。当被订阅者的状态发生改变时,所有订阅者都能收到消息,并做出各自具体的响应。

示例代码:

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
class Listener {
public:
virtual void OnReceived(std::string msg) = 0;
};

class Subject {
public:
void RigistryListener(Listener* listener) {
listeners_.push_back(listener);
}

void RemoveListener(Listener* list) {
listeners_.remove_if([list](Listener* l) { return l == list; });
}

void Notify() {
std::for_each(listeners_.begin(), listeners_.end(),
[this](Listener* l) { l->OnReceived(status_); });
}

void SetStatus(std::string s) {
status_ = s;
Notify();
}

private:
std::list<Listener*> listeners_;
std::string status_;
};

class ListenerA : public Listener {
public:
virtual void OnReceived(std::string msg) override {
printf("ListenerA Subject status changed: %s\n", msg.c_str());
}
};

class ListenerB : public Listener {
public:
virtual void OnReceived(std::string msg) override {
printf("ListenerB Subject status changed: %s\n", msg.c_str());
}
};