Why is MouseAdapter an adapter?

2020-02-05 12:17发布

The name (and javadocs) imply that MouseAdapter is an adapter (the design pattern). But I don't see it as such - it doesn't adapt anything to anything, at first sight at least

The only adaptation that happens is that you can pass an instance of MouseAdapter to any method that expects either of the interfaces. So, you make it possible to use a MouseListener instance where only MouseMotionListener is expected. But there is no "translation" happening. And it does not conform to the UML of GoF - in the "class adapter" version it is expected that a call to one method invokes a method from the adaptee.

So, is that an adapter (design pattern), or is it just a random name that causes confusion?

4条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-05 12:54

I know there is already an accepted answer for this question, but this same question was asked here:

MouseAdapter: which pattern does it use?

See there for more deatils, but the MouseAdapter adapts the very awkaward MouseListener interface into a more usable form.

查看更多
The star\"
3楼-- · 2020-02-05 13:03

Yes, it is not an adapter in the sense of GoF pattern because it does not adapt anything. It can be considered an instance of Abstract Class pattern [woolf97]:

The superclass may provide a complete implementation that is a default or minimal implementation.

查看更多
beautiful°
4楼-- · 2020-02-05 13:10

MouseAdapter first appeared in Java 1.1 released in Feb 1997. This means that it was developed sometime in 1996 (or 1995?)

UML (in its draft) was completed by 1997.

The first GoF book on design patterns was published in 1995.

So, I don't think that Adapter in MouseAdapter had anything to do with the corresponding design pattern. Or, even if it did, developers just had no unified language to express design patterns which would make it very hard to comprehend the real meaning.

查看更多
够拽才男人
5楼-- · 2020-02-05 13:14

As other answers have said, it's not a GoF Adapter pattern. The main purpose of it is to enable one to implement MouseListener (or MouseMotionListener) by over-riding just the desired methods in MouseAdapter (often just mouseClicked()) rather than having to create pointless empty implementations of all the other methods. It therefore saves a lot of unnecessary code, especially when using anonymous event listeners. For example (taken from here)

    someObject.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            ...//Event listener implementation goes here...
        }
    });
查看更多
登录 后发表回答