Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this really an example of the adapter pattern?

I have an interface -- "EventHandler" -- that declares several methods.

public interface EventHandler {
    void handleEvent1();

    void handleEvent2();

    void handleEvent3();

    void handleEvent4();
}

I also have a class -- "EventHandlerAdapter" -- that implements EventHandler. However, it doesn't actually "implement" anything. The point is, if another class wants to implement EventHandler, but not all of its methods, it can simply extend EventHandlerAdapter and only override the methods it wants to.

public class EventHandlerAdapter implements EventHandler {
    public void handleEvent1() {}

    public void handleEvent2() {}

    public void handleEvent3() {}

    public void handleEvent4() {}
}

I've seen something like this on more than one occasion. The name "EventHandlerAdapter" suggests to me that it is an example of the adapter pattern... but is it really? I thought the point of an adapter was to translate an existing implementation into something else. I don't see how this is the case here.

If it isn't an example of the adapter pattern, what is it? Surely something like this has been identified.

like image 227
someguy Avatar asked Aug 24 '10 13:08

someguy


1 Answers

No, this is not an example of an Adapter Pattern, as defined here:

http://en.wikipedia.org/wiki/Adapter_pattern

However, in Java Event handling, the term Adapter is frequently used as you mentioned. Even though the word "Adapter" is the same in both, they do not refer to the same thing. The Adapters that appear in the java.awt.event package are there to make it easy to create an event handler that handles only one method without having to write a bunch of empty methods. They are only shortcut classes.

The Java Event API typically has consistent naming for these classes. When there is a SomeEvent event class, there is a SomeListener interface to listen to the event and a SomeAdapter class implementing the listener interface with empty methods. Not all events have all three of these parts, but there is consistency in the naming and function of the three.

In the example you provided, I would rename the class EventAdapter to be consistent with the existing Java API.

like image 92
Erick Robertson Avatar answered Oct 12 '22 23:10

Erick Robertson