-
Notifications
You must be signed in to change notification settings - Fork 1
/
mediator.java
72 lines (57 loc) · 1.72 KB
/
mediator.java
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
interface Mediator {
void send(Colleague colleague, String message);
}
abstract class Colleague {
protected Mediator mediator;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
abstract void receive(String message);
}
class ConcreteMediator implements Mediator {
private Colleague colleague1;
private Colleague colleague2;
public void setColleague1(Colleague colleague1) {
this.colleague1 = colleague1;
}
public void setColleague2(Colleague colleague2) {
this.colleague2 = colleague2;
}
@Override
public void send(Colleague colleague, String message) {
if(colleague == colleague1){
colleague2.receive(message);
} else {
colleague1.receive(message);
}
}
}
class ConcreteColleague1 extends Colleague {
public ConcreteColleague1(Mediator mediator) {
super(mediator);
}
@Override
void receive(String message) {
System.out.printf("ConcreteColleage1 received: %s\n", message);
}
}
class ConcreteColleague2 extends Colleague {
public ConcreteColleague2(Mediator mediator) {
super(mediator);
}
@Override
void receive(String message) {
System.out.printf("ConcreteColleage2 received: %s\n", message);
}
}
public class Main {
public static void main(String[] args) {
ConcreteMediator mediator = new ConcreteMediator();
Colleague colleague1 = new ConcreteColleague1(mediator);
Colleague colleague2 = new ConcreteColleague2(mediator);
mediator.setColleague1(colleague1);
mediator.setColleague2(colleague2);
mediator.send(colleague1, "Hello");
mediator.send(colleague2, "World");
}
}