1.適配器模式的定義
Adapter Pattern:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interface.
將一個類的接口變換成客戶端所期待的另一種接口,從而使原本因接口不匹配而無法在一起工作的兩個類能夠一起工作。
2.通用類圖
適配器模式中有三個主要對象。
Target:
轉換成的目標接口,即將其他類轉換為此Target接口
Adaptee:
被轉換的類
Adapter:
適配器,通過實現Target接口並繼承Adaptee類,並重寫Target接口方法來實現適配
類圖如下:

實現代碼如下:
Target類:
public interface Target {
/**
* request
*/
void request();
}
Adaptee類:
public class Adaptee {
public void doSomething(){
System.out.println("Do something!");
}
}
Adapter類:
public class Adapter extends Adaptee implements Target {
@Override
public void request() {
doSomething();
}
}
Client類:
public class Client {
public static void main(String[] args) throws Exception {
Target target = new Adapter();
target.request();
}
}
3.優點
1.可以使兩個無關聯的類一起運行
2.靈活性好,當不需要此適配器的時候,只需要將此類摘除掉即可
4.總結
適配器模式通常用來解決在功能變動時,解決接口不相容的問題,在系統設計階段不應該使用此中模式
