文章目录
  1. 中介者模式

中介者模式

  • 用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散。可以独立地改变他们之间的交互。i
    Mediator
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public interface Mediator {
void change(Module module);
}
public class VolMediator implements Mediator {
private Speaker speaker;
private VolButton volButton;
@Override
public void change(Module module) {
if (volButton == module) {
if (volButton.status==0){
speaker.louder(volButton.vol);
System.out.println("音量加"+volButton.vol);
}else{
speaker.lighter(volButton.vol);
System.out.println("音量减"+volButton.vol);
}
}
}
public void setSpeaker(Speaker speaker) {
this.speaker = speaker;
}
public void setVolButton(VolButton volButton) {
this.volButton = volButton;
}
}
public abstract class Module {
protected Mediator mediator;
public Module(Mediator mediator){
this.mediator=mediator;
}
}
public class Speaker extends Module{
public Speaker(Mediator mediator){
super(mediator);
}
public void louder(int i){
System.out.println("音量增加" + i);
}
public void lighter(int i){
System.out.println("音量减少"+i);
}
}
public class VolButton extends Module {
public int status=0;
public int vol=0;
public VolButton(Mediator mediator){
super(mediator);
}
public void up(int i){
status=0;
vol=i;
mediator.change(this);
}
public void down(int i){
status=1;
vol=i;
mediator.change(this);
}
}
public class App {
public static void main(String[] args) {
VolMediator mediator=new VolMediator();
Speaker speaker=new Speaker(mediator);
VolButton volButton=new VolButton(mediator);
mediator.setSpeaker(speaker);
mediator.setVolButton(volButton);
volButton.up(10);
volButton.down(10);
}
}
文章目录
  1. 中介者模式