Adapter mode:
The interface of a class is transformed into another interface that the client expects, so that the two classes that cannot work together due to interface mismatch can work together.
The adapter has two modes:
Class adapter Mode
Object Adapter Mode
The following describes the class adapter mode.
Role involved in the adapter mode of the class:
Target role: This is the expected interface. The target cannot be a class.
Source role: Existing interface to be adapted
Adapter role: the adapter class is the core of this mode. The adapter converts the source interface to the target interface. Obviously, this role cannot be an interface, but must be a specific class.
Effect of the object's adapter mode:
1. An adapter can adapt multiple sources to the same target. In other words, the same adapter can adapt both the source class and its subclass to the target interface.
2. Compared with the adapter mode of the class, it is not easy to replace the method of the source class.
3. Although it is not easy to replace the method of the source class, it is easy to add a new method and applies to all sources.
Let's talk a little bit about it. Go directly to the code and first abstract a scenario:
Chinese and Korean people talk about business, but both parties do not understand the language of the other party. What should I do? There are two solutions: one is to let the Koreans learn to speak Chinese, and the other is to let the Koreans find a translation that can understand the language of both parties. Undoubtedly, the first solution is time-consuming and does not meet the requirements. Therefore, the second solution meets the requirements. The second solution here is a typical adapter mode.
Source role:
public interface People {void speak();}
Target role:
Public class Korean {public void be () {system. Out. println ("I Am a Korean ");}}
// This is a soy sauce playing role, just compare public class Chinese {public void be () {system. Out. println ("I am Chinese ");}}
Adapter:
Public class adapter extends Korean implements people {@ overridepublic void speak () {super. be (); system. Out. println ("I can speak Chinese ...");}}
The implementation method is based on Android. Java directly writes a test class to implement it in the main method:
mbtnAdapter.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {People korean = new Adapter();korean.speak();}});
Output:
Now, Koreans can speak Chinese. Let's talk about business.