在Java中如果要定義事件處理的方式,必須實作EventListener的子介面,例如實作 WindowListener來定義一些視窗事件的處理方式,WindowListener中定義了七個方法:
public interface WindowListener extends EventListener {
public void windowOpened(WindowEvent e);
public void windowClosing(WindowEvent e);
public void windowClosed(WindowEvent e);
public void windowIconified(WindowEvent e);
public void windowDeiconified(WindowEvent e);
public void windowActivated(WindowEvent e);
public void windowDecativated(WindowEvent e);
}
可以定義一個類別來實作這個介面,以完全想要的事件處理,例如:
public class WindowEventHandler implements WindowListener {
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDecativated(WindowEvent e) {}
}
然而這有個缺點,實作介面的原則是您必須實作當中所定義的所有方法,即使您對某些事件並不感興趣,您也必須實作一個沒有內容的空方法,代表您已經實作了介面中定義的方法,然而有時,您並不知道介面中到底定義了幾個方法,或是知道也不知道方法的確切名稱與參數,即使您查了API,在程式中寫下一堆沒有實作內容的方法也是很煩人的一件事。
WindowAdapter類別預先實作了WindowListener介面,每個方法中都是空的實作,如下所示:
public abstract class WindowAdapter
implements WindowListener {
public void windowOpened(WindowEvent e) {}
public void windowClosing(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDecativated(WindowEvent e) {}
}
可以繼承WindowAdapter類別,並重新定義一些您所感興趣的事件,如此一來,就可以避開之前所提及的,直接實作 WindowListener介面的缺點,如下所示:
public class WindowEventHandler extends WindowAdapter {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
}
這就是Default Adapter模式,它使用一個中介的Adapter類別來將真正感興趣的事件實作類別,配接至事件處理介面,上面的程式其 UML 圖如下:
將上圖一般化,Default Adapter模式的結構如下所示: