组件之间存在复杂依赖的时候,可以构造一个中介者统一管理组件之间的通讯。

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
class Mediator {
public:
virtual ~Mediator() {}
virtual void notify(Component* sender, std::string event) = 0;
};

class AuthenticationDialog: public Mediator {
private:
std::string title;
Checkbox *loginOrRegisterChkBx;
Textbox *loginUsername, *loginPassword;
Textbox *registrationUsername, *registrationPassword, *registrationEmail;
Button *okBtn, *cancelBtn;

public:
AuthenticationDialog() {
// create all components by pasing the current
// mediator into their constructors to establish links
}
void notify(Component* sender, std::string event) override {
if (sender == loginOrRegisterChkBx && event == "check")
if (loginOrRegisterChkBx->checked) title = "Log in";
else title = "Register";
if (sender == okBtn && event == "click")
if (loginOrRegister->checked) {
// try to find the user
if (!found) // show error msg
} else {
// create user account and log that user in
}

}
};

class Component {
Mediator* dialog;
public:
Component(Mediator* m): dialog(m) {}
void click() {
dialog->notify(this, "click");
}
void keypress() {
dialog->notify(this, "keypress");
}
};

class Button: public Component {
// ...
};

class Textbox: public Component {
// ...
};

class Checkbox: public Component {
public:
void check {
dialog->notify(this, "check");
}
}