感想
桥接模式:将实现与抽象放在两个不同的类层次中,使两个层次可以对立改变。
桥接模式原理:系统有多维度角度分类时,而每一种分类又有可能变化,考虑使用桥接模式桥接的目的是分离抽象与实现,使抽象和实现可以对立变化。
这里以遥控器和电视都有可能需要拓展为例子:
a.先定义遥控器的接口:
1 | public interface Control { |
b1.实现遥控器接口,并形成不同牌子的遥控器实体类,以下是LG品牌的:
1 | public class LGControl implements Control { |
b2.以下是夏普品牌的:
1 | public class SharpControl implements Control { |
b3.以下是索尼品牌的:
1 | public class SonyControl implements Control { |
c.创建电视遥控的超类:
1 | public abstract class TvControlabs { |
d1.实现电视遥控:
1 | public class TvControl extends TvControlabs { |
d2.再实现电视遥控,这里添加多了setChannel和Back方法: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
53public class newTvControl extends TvControlabs {
private int ch = 0;
private boolean ison = false;
private int prech = 0;
public newTvControl(Control mControl) {
super(mControl);
}
public void Onoff() {
if (ison) {
ison = false;
mControl.Off();
} else {
ison = true;
mControl.On();
}
}
public void nextChannel() {
prech = ch;
ch++;
mControl.setChannel(ch);
}
public void preChannel() {
prech = ch;
ch--;
if (ch < 0) {
ch = 200;
}
mControl.setChannel(ch);
}
public void setChannel(int nch) {
prech = ch;
ch = nch;
mControl.setChannel(ch);
}
public void Back() {
mControl.setChannel(prech);
}
}
e.客户端使用:
1 | public class MainTest { |