Design Pattern: Default Adapter 模式

简介:

在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);
    }
}
目录
相关文章
|
6月前
|
JavaScript
error Component name “Login“ should always be multi-word vue/multi-word-component-names【已解决】
error Component name “Login“ should always be multi-word vue/multi-word-component-names【已解决】
312 1
913 error Component name “home“ should always be multi-word vuemulti-word-component-names
913 error Component name “home“ should always be multi-word vuemulti-word-component-names
104 0
|
JavaScript 前端开发 开发者
Component name “xxx“ should always be multi-word
Component name “xxx“ should always be multi-word
Component name “xxx“ should always be multi-word
|
Java 索引 Spring
Circular view path xxx would dispatch back to the current handler URL
版权声明:本文为 testcs_dn(微wx笑) 原创文章,非商用自由转载-保持署名-注明出处,谢谢。 https://blog.csdn.net/testcs_dn/article/details/79700275 ...
5483 0