適配器模式(Adapter):將一個類的接口轉換成客戶端(client)希望的另外一個接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些類可以一起工作。 Convert the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
這個有類adaptee方法method1()和method2()繼承自ownInterface接口,現在有一個接口target有三個方法,需要用到method1()或者method2(),為了不造成耦合,需要一個適配器adapter將adaptee進行適配(java中有直接繼承adaptee和 委托 方法),這樣client就可以通過target調用adaptee的方法或者是自己實現的another
適配器模式分為類適配器和對象適配器. 類適配器的實現就是通過繼承adaaptee實現適配,對象適配器就是用委托的方式實現適配
原始類
// 原始類public class Adaptee implements OwnInterface { public void method1() { System.out.類適配器public class Adapter extends Adaptee implements Target{ public void method1() { super.method1(); } public void method2() { super.method2(); } public void method3() { System.out.println("自己實現的功能1"); }}對象適配器
public class Adapter implements Target{ //委托或者代理 private Adaptee adaptee = new Adaptee(); public void method1() { this.adaptee.method1(); } public void method2() { this.adaptee.method2(); } public void method3() { System.out.println("自己實現的功能1"); }}client類
public class Client { public static void main(String[] args) { // 使用普通功能類 Target another= new Another(); another.method1(); // 使用特殊功能類,即適配類, // 需要先創建一個被適配類的對象作為參數 Target adapter = new Adapter(); adapter.method1(); }}新聞熱點
疑難解答