forked from hamed-rezaee/dart_design_patterns_collection
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediator.dart
43 lines (33 loc) · 1.08 KB
/
mediator.dart
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
abstract class BaseMediator<T> {
final List<BaseColleague<T>> _colleagues = <BaseColleague<T>>[];
void register(BaseColleague<T> colleague) => _colleagues.add(colleague);
void notify(BaseColleague<T> sender, T message) {
for (final BaseColleague<T> colleague in _colleagues) {
if (colleague != sender) {
colleague.receive(message);
}
}
}
}
abstract class BaseColleague<T> {
BaseColleague(this._mediator);
final BaseMediator<T> _mediator;
void send(T message) => _mediator.notify(this, message);
void receive(T message);
}
class ConcreteMediator extends BaseMediator<String> {
@override
void notify(BaseColleague<String> sender, String message) {
for (final BaseColleague<String> colleague in _colleagues) {
if (colleague != sender) {
colleague.receive(message);
}
}
}
}
class ConcreteColleague extends BaseColleague<String> {
ConcreteColleague(BaseMediator<String> mediator, this.name) : super(mediator);
String name;
@override
void receive(String message) => print('$name received message: $message');
}