【設計模式】(十三)–結構型模式–適配器模式
適配器模式定義
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn`t otherwise because of incompatible interface.
意思是:講一個類的接口變換成客戶端所期待的另一個接口,從而使原本因爲接口不匹配而無法在一起工作的兩個類能在一起工作。
適配器模式一般有3個要素:
- Target 支持的新接口
- Adapter 將調用轉發給Adaptee的適配器類
- Adaptee 需要適配的舊代碼
適配器模式的有點
- 1、可以讓任何兩個沒有關聯的類一起運行。 、
- 2、提高了類的複用。
- 3、增加了類的透明度。
- 4、靈活性好。
適配器模式的使用場景
- 對已經在線上運行的系統進行拓展時,已有類的功能已存在但是和預期功能又出入時,可以通過適配器進行轉化,轉成符合目標要求的可以使用的類
簡單的實現
類圖
實現
public class CookerAdapter extends Wok implements FryingPan {
@Override
public void fry() {
super.cook();
System.out.println("開始煎食物");
}
public static void main(String[] args) {
FryingPan fryingPan = new CookerAdapter();
fryingPan.fry();
}
}
/**
* 炒鍋
*/
public class Wok {
public void cook() {
System.out.println("開始烹飪");
}
}
/**
* 煎鍋
*/
public interface FryingPan {
void fry();
}
執行結果
實現解讀
有一個Wok,通過適配實現了煎鍋的功能。