Single Interface Adapter in Adapter Mode

In java, in addition to the object adapter , there is a more common adapter, that is, a single-interface adapter, which allows users to use the interface more conveniently.

  For example, the MouseListener interface in the java.awt.event package defines a total of five methods:

1 void mouseClicked(MouseEvent arg0) {}
2 void mouseEntered(MouseEvent arg0) {}
3 void mouseExited(MouseEvent arg0) {}
4 void mousePressed(MouseEvent arg0) {}
5 void mouseReleased(MouseEvent arg0) {}

  When an object of a class that implements the MouseListener interface is needed, then when writing and creating an object, the class must implement all the methods in the MouseListener interface, but often users only need to implement a certain method in the interface, so it appears A lot of useless code.

  If a single interface adapter is used, the code writing can be reduced, and the user can concentrate on the implementation of the required methods.

  A single-interface adapter for an interface is a class that already implements the interface and gives a default implementation for each method in the interface. For example, the MouseAdapter in the java.awt.event package is a single-interface adapter in the MouseListener interface, which implements all five methods in the MouseListener interface without any operation, that is, there are no statements in the five method bodies.

  When the user needs another instance of a class that implements the MouseListener interface, he only needs to write a subclass of MouseAdapter and override the interface methods he needs in the subclass. E.g:

  

copy code
 1 package com.adatpe;
 2 
 3 import java.awt.event.MouseAdapter;
 4 import java.awt.event.MouseEvent;
 5 
 6 public class HandleEvent extends MouseAdapter {
 7     @Override
 8     public void mousePressed(MouseEvent arg0) {
 9         // TODO Auto-generated method stub
10         super.mousePressed(arg0);
11     }
12     
13 }
copy code

 

  This eliminates the need to implement all the methods of the interface, reducing a lot of useless code.

  In fact, in the java API, if there are more than one method in an interface, the corresponding single-interface adapter is provided for the interface, such as the familiar WindowAdapter, KeyAdapter, etc.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326354459&siteId=291194637