概述
將一個類的接口轉換成用戶希望的另外一個接口,Adapter模式使得原本由于接口不兼容而不能一起工作的那些類可以在一起工作。
兩種實現(xiàn)方式
1.類的適配器模式:
2.對象的適配器模式:
類的適配器模式的UML圖,如下:
類的適配器模式把適配的類的API轉換成為目標類的API。
上圖設計的角色有:
目標角色(Target):這就是所期待得到的接口。
源角色(Adapee):現(xiàn)在需要適配的接口。
適配器角色(Adapter):是本模式的核心,適配器把源接口轉換成目標接口。
代碼示例:
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
|
interface Target{ void method1(); void method2(); //期待得到該方法 } //源類中不具備method2中的方法。 class Adaptee{ public void method1(){ System.out.println( "method1" ); } } class Adapter extends Adaptee implements Target{ @Override public void method2() { System.out.println( "this is target method" ); } } public class MainTest { public static void main( String arg[]) { Target target = new Adapter(); target.method2(); } } |
對象的適配器模式的UMl圖,如下:
核心思路與類的適配器模式相同,只是將Adapter類修改,不繼承Adaptee類,而是持有Adaptee類的引用。代碼如下:
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
|
interface Target{ void method1(); void method2(); } class Adaptee{ public void method1(){ System.out.println( "method1" ); } } class Adapter implements Target{ private Adaptee adaptee; public Adapter(Adaptee adaptee){ this .adaptee = adaptee; } @Override public void method2() { System.out.println( "this is target method" ); } @Override public void method1() { // TODO Auto-generated method stub adaptee.method1(); } } public class MainTest { public static void main(String arg[]) { Target target = new Adapter( new Adaptee()); target.method2(); } } |
適配器模式的優(yōu)缺點:
更好的復用性,更好的擴展性。系統(tǒng)需要使用現(xiàn)有的類,而此類的接口不符合系統(tǒng)的需要,那么通過適配器模式就可以讓這些功能得到更好的復用。在實現(xiàn)適配器功能的時候,可以調用自己開發(fā)的功能,從而自然地擴展系統(tǒng)的功能。
缺點:過多的使用適配器,會讓系統(tǒng)非常凌亂,不易整體把握。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。