一、適用場景
如生活中鍵盤有USB接口的和ps/2接口的。我們手上有一個ps/2接口的鍵盤但筆記本電腦只有USB接口,我們只要找一個接口轉換器就能讓鍵盤在筆記本電腦上使用了。
適配器模式是將一個類的接口轉換成客戶希望的另一個接口,使得原本由於接口不兼容而不能相互調用的類能夠一起工作。
二、實現
適配器的實現需要3個構件:
- 目標接口 (Target, 即USB接口)
- 需要適配的類(Adaptee, 即源接口 ps/2)
- 適配器(Adapter, 即轉換器)
我們以ps/2到USB接口適配器爲例,來實現一個適配器模式的例子。
1. 先定義USB接口,指定功能
public interface USB {
public void typeWords(); //具有打字的功能
}
2. 定義Adapter,去Implements USB接口
public class Adapter implements USB {
private Ps2KeyBoard keyboard;
public Adapter(Ps2KeyBoard keyboard) {
this.keyboard = keyboard;
}
@Override
public void typeWords() {
keyboard.typeWords();
}
}
3. Adapter用到了Ps2KeyBoard類,也就是真正幹活的部分,要創建這個類,並在指定接口中調用Ps2KeyBoard對象的打字功能。
public class Ps2KeyBoard {
public void typeWords(){
System.out.println("ps2keyboard is typing words.");
}
}
4. Client調用這個Adapter, 在Adapter中傳入Ps2KeyBoard對象用來幹活,就通過Adapter實現了用Ps2鍵盤打字的功能。
public class Client {
public void typeWords(USB usb){
usb.typeWords();
}
public static void main(String[] args) {
Client client = new Client();
client.typeWords(new Adapter(new Ps2KeyBoard()));
}
}
調用結果