Monday, 18 April 2016

Adaptor pattern : Example 1


The famous adapter classes in Java API are WindowAdapter, ComponentAdapter, ContainerAdapter, FocusAdapter, KeyAdapter, MouseAdapter and MouseMotionAdapter.

WindowListner interface has seven methods. Whenever your class implements such interface, you have to implements all of the seven methods. WindowAdapter class implements WindowListener interface and make seven empty implementation.

When you class subclass WindowAdapter class, you may choose the method you want without restrictions. The following give such an example.

Make a adapter class to implement listener.
public class WindowAdapter implements WindowListner {
   public void windowClosed(WindowEvent e) {}
   public void windowOpened(WindowEvent e) {}
   public void windowIconified(WindowEvent e) {}
   public void windowDeiconified(WindowEvent e) {}
   public void windowActivated(WindowEvent e) {}
   public void windowDeactivated(WindowEvent e) {}
   public void windowClosing(WindowEvent e) {}
}

Then, make a subclass to give custom functionality and use it
class Closer extends WindowAdapter {
    public void windowClosing(WindowEvent e) {
         System.exit(0);
    }
}

//.... use of Closer class
addWindowListener(new Closer());

No comments:

Post a Comment

Note: only a member of this blog may post a comment.