Design patterns Adapter Java Example


Example

A great existing example of the Adapter pattern can be found in the SWT MouseListener and MouseAdapter classes.

The MouseListener interface looks as follows:

public interface MouseListener extends SWTEventListener {
    public void mouseDoubleClick(MouseEvent e);
    public void mouseDown(MouseEvent e);
    public void mouseUp(MouseEvent e);
}

Now imagine a scenario where you are building a UI and adding these listeners, but most of the time you don't care about anything other than when something is single clicked (mouseUp). You wouldn't want to constantly be creating empty implementations:

obj.addMouseListener(new MouseListener() {

    @Override
    public void mouseDoubleClick(MouseEvent e) {
    }

    @Override
    public void mouseDown(MouseEvent e) {
    }

    @Override
    public void mouseUp(MouseEvent e) {
        // Do the things
    }

});

Instead, we can use MouseAdapter:

public abstract class MouseAdapter implements MouseListener {
    public void mouseDoubleClick(MouseEvent e) { }
    public void mouseDown(MouseEvent e) { }
    public void mouseUp(MouseEvent e) { }
}

By providing empty, default implementations, we are free to override only those methods which we care about from the adapter. Following from the above example:

obj.addMouseListener(new MouseAdapter() {

    @Override
    public void mouseUp(MouseEvent e) {
        // Do the things
    }

});