理解適配器模式之前,可以先來看一下轉換插頭,兩者的思想其實是一樣的
就是上圖中的這個樣子,當你出國旅行的時候,可能會用到這樣一個東西,你的筆記本電腦直接插到國外的插座上是插不進去的,需要用一個轉換插頭,先讓轉換插頭插到插座上,然後你的筆記本電腦插到轉換插頭上,這樣就解決了問題
而這個轉換插頭,就是我們今天要說的適配器模式,在現實中的一個實現
適配器模式的定義:
適配器模式(Adapter):將一個類的接口,轉換成客戶希望的另外一個接口,Adapter模式使得原本由於接口不兼容而不能一起工作的類,可以一起工作
適配器模式的類圖:
適配器模式的應用場景:
首先,咱們有一個現成的類,完成了一些特定的功能,現在要複用這個舊的類的功能,讓它實現新的接口,我們定義一個新的類,讓這個新的類實現新的接口,實現的方法就是調用舊的類
這樣就實現了適配器
依照上邊的類圖,我們可以寫出適配器模式的示例代碼:
public interface Target {
void doSomething();
}
public class Adaptee {
public void service(){
System.out.println("我是原始的類");
}
}
public class Adapter implements Target {
public Adaptee adaptee;
@Override
public void doSomething() {
adaptee.service();
}
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
}
public class AdapterClient {
public static void main(String[] args) {
Target target = new Adapter(new Adaptee());
target.doSomething();
}
}