如果一个类只希望实现接口中的部分方法,这时就可以考虑使用缺省适配模式。新建一个抽象类实现接口,空实现接口中所有的方法,新的类继承该抽象类,覆盖希望实现的方法即可。
以AWT中的常用的监听器为例,希望给Frame加上一个WindowListener,frame.addWindowListener()的参数是new WindowListener(),也就是可以像下面这样写代码:
frame.addWindowListener(new WindowListener(){ @Override public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } @Override public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } });
如果只是想重写windowClosing方法,上面的写法会显得很冗余,而且别人都知道再什么。
给Frame加上一个WindowListener,正确的方法如下:
frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
可以看WindowAdapter的源码,所有的实现都是空实现:
public abstract class WindowAdapter implements WindowListener, WindowStateListener, WindowFocusListener { 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 windowDeactivated(WindowEvent e) {} public void windowStateChanged(WindowEvent e) {} public void windowGainedFocus(WindowEvent e) {} public void windowLostFocus(WindowEvent e) {} }
上面就是缺省适配模式的一个很好的例子。
AWT中有很多使用缺省适配模式的实例,如下所示:
鲁智深是和尚,但是却不吃斋,念经,打坐,撞钟。如果是直接继承自和尚这个接口,那鲁智深就不是和尚了。可以让抽象类天星继承和尚接口,鲁智深作为天星的子类即可。