1.類適配器
使用情況:利用第三方類來完成給定的接口期望。
示例演示:
首先有一個接口,期望用這個接口來實現求和操作:
1
public interface Operation{
2
public int add(int a,int b);
3
}
4
現在發現一個第三方類,它有一個方法剛好實現了Operation的add方法。

2

3

4

1
public class OtherOperation{
2
public int otherAdd(int a,int b){
3
return a + b;
4
}
5
}
6
為了利用第三方類來實現Operation的期望,我們可以采用如下方式:

2

3

4

5

6

1
public class AdapterOperation extends OtherOperation implements Operation{
2
public int add(int a,int b){
3
return otherAdd(a,b);
4
}
5
}
6
以上就是適配器的實現方法之一,類適配器。它就是用適配器類去繼承已有的第三方類,然后第三方類的方法來實現預期的功能。
2

3

4

5

6

2.對象適配器
使用情況一:當給定的接口功能比較多時,并且第三方的實現類也比較多時,就無法利用類適配器的方式來實現預期功能了,這時可采用對象適配器方式。
示例演示:假如客戶接口期望的功能不止一個,而是多個:
1
public interface Operation{
2
public int add(int a,int b);
3
public int minus(int a,int b);
4
public int multiplied(int a,int b);
5
}
6
而能提供這些實現的原可能不止一個:

2

3

4

5

6

1
public class OtherAdd{
2
public int otherAdd(int a,int b){
3
return a + b;
4
}
5
}
6
7
public class OtherMinus{
8
public int minus(int a,int b){
9
return a - b;
10
}
11
}
12
13
public class OtherMultiplied{
14
public int multiplied(int a,int b){
15
return a * b;
16
}
17
}
18
由于java是不能實現多繼承的,所以我們不能通過構建一個適配器,讓他來繼承所有原以完成我們的期望,這時候怎么辦呢?只能用適配器的另一種實現--對象適配器:

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

1
public class AdapterOperation implements Operation{
2
private OtherAdd add;
3
private OtherMinus minus;
4
private OtherMultiplied multiplied;
5
6
public void setAdd(OtherAdd add){
7
this.add = add;
8
}
9
10
public void setMinus(OtherMinus minus){
11
this.minus = minus;
12
}
13
14
public void setMultiplied(OtherMultiplied multiplied){
15
this.multiplied = multiplied;
16
}
17
18
//適配加法運算
19
public int add(int a,int b){
20
return add.otherAdd(a,b);
21
}
22
23
//適配減法運算
24
public int minus(int a,int b){
25
return minus.minus(a,b);
26
}
27
28
//適配乘法運算
29
public int multiplied(int a,int b){
30
return multiplied.multiplied(a,b);
31
}
32
}
33
上面代碼很明顯,適配器并不是通過繼承來獲取適配類(原)的功能的,而是通過適配類的對象來獲取的,這就解決了java不能多繼承所帶來的不便了。這也是java提倡的編程思想之一,即盡量使用聚合不要使用繼承。
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

使用情況二:所提供的需求并不是一個明確的接口,而是一個類B,并沒有定義期望的方法,并且要求B能夠何留類A的功能,如下 :















這時候,我們發現類C已經提供了實現減法的函數。
1
public class C{
2
public int minus(int a,int b){
3
return a - b;
4
}
5
}
6
為了避免重復去設計該函數,我們決定引入C類,通過適配C類來達到我們的期望,但問題是A和C都是一個具體類,我們無法讓B同時繼承這個兩個類,而B繼承A又是必須的,所以我們只能考慮把C給內聚到B內部,對象適配器又得派上用場了。

2

3

4

5

6

1
public class B extends A{
2
3
private C c;
4
5
B(){
6
super();
7
}
8
9
public void setMinus(C c){
10
this.c= c;
11
}
12
13
public int minus(int a,int b){
14
return c.minus(a,b);
15
}
16
}
17

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

3.隱藏目標接口的抽象適配器
一個接口中有多個抽象方法,而在實際情況中,所用到的實現類并不一定要實現它的所有方法,在這種情況下,為避免在書定實現類的多余代碼,可以預先給定一個抽象的適配器類,這個類實現了接口的所有方法,并且所有的實現都是空實現。