概述
將一個類的接口轉換成用戶希望的另外一個接口,Adapter模式使得原本由於接口不兼容而不能一起工作的那些類可以在一起工作。
兩種實現方式
1.類的適配器模式:
2.對象的適配器模式:
類的適配器模式的UML圖,如下:
類的適配器模式把適配的類的API轉換成為目標類的API。
上圖設計的角色有:
目標角色(Target):這就是所期待得到的接口。
源角色(Adapee):現在需要適配的接口。
適配器角色(Adapter):是本模式的核心,適配器把源接口轉換成目標接口。
代碼示例:
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類的引用。代碼如下:
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(); }}適配器模式的優缺點:
更好的複用性,更好的擴展性。系統需要使用現有的類,而此類的接口不符合系統的需要,那麼通過適配器模式就可以讓這些功能得到更好的複用。在實現適配器功能的時候,可以調用自己開發的功能,從而自然地擴展系統的功能。
缺點:過多的使用適配器,會讓系統非常凌亂,不易整體把握。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。