“This is the 23rd day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

Java adapter pattern

The Adapter Pattern acts as a bridge between two incompatible interfaces. This type of design pattern is structural in that it combines the functionality of two separate interfaces.

This pattern involves a single class that is responsible for adding separate or incompatible interface functionality. For a real-world example, a card reader acts as an adapter between a memory card and a laptop. You insert the memory card into the card reader, and then insert the card reader into the notebook so that the memory card can be read from the notebook.

The following example demonstrates the use of the adapter pattern. Among them, the audio player device can only play MP3 files, by using a more advanced audio player to play VLC and MP4 files.

introduce

Intent: To convert the interface of a class to another interface that the customer wants. The adapter pattern makes it possible for classes to work together that would otherwise not work because of interface incompatibilities.

Main solution: Main solution in software systems, it is often necessary to put some “existing objects” into a new environment, and the new environment requirements of the interface is the current object can not meet.

When to use:

⒈ The system needs to use existing classes, and such interfaces do not meet the needs of the system.

⒉ Want to build a reusable class, used to work with some classes that do not have much relationship with each other, including some classes that may be introduced in the future, these source classes may not have a consistent interface.

⒊ Insert a class into another class family by interface transformation. (For example, tigers and birds, now more than a flying tiger, without the need to increase the entity, add an adapter, containing a tiger object in the interface to achieve flying.)

How to resolve it: Inheritance or dependency (recommended).

Key code: The adapter inherits or relies on existing objects to implement the desired target interface.

Application examples:

⒈ American electrical 110V, China 220V, there is an adapter to convert 110V into 220V.

⒉ The JAVA JDK 1.1 provides the Enumeration interface, and the 1.2 provides the Iterator interface. If you want to use the 1.2 JDK, you need to convert the Enumeration interface to the Iterator interface. This is where the adapter pattern is needed.

⒊ Run WINDOWS programs on LINUX. 4. JDBC in JAVA

Advantages:

⒈ Any two unrelated classes can be run together.

⒉ Improves class reuse.

⒊ Added class transparency.

4. It has good flexibility.

Disadvantages:

⒈ Too much use of adapters will make the system very messy and not easy to grasp as a whole. For example, clearly see is called A interface, in fact, internal adaptation into the IMPLEMENTATION of THE B interface, A system if too much of this situation, is tantamount to A disaster. So if you don’t have to, you can skip the adapter and refactor your system directly.

2. Since JAVA inherits at most one class, at most one adaptor class can be adapted, and the target class must be abstract.

Usage scenario: The adapter pattern should be considered when you are motivated to modify the interface of a functioning system.

Note: Adapters are not added during detailed design, but rather to solve problems of projects in service.

implementation

We have a MediaPlayer interface and an entity class AudioPlayer that implements the MediaPlayer interface. By default, AudioPlayer can play audio files in mp3 format.

We also have another interface AdvancedMediaPlayer and an entity class that implements the AdvancedMediaPlayer interface. This class can play VLC and MP4 files.

We want AudioPlayer to play audio files in other formats. To do this, we need to create a MediaAdapter class that implements the MediaPlayer interface and use the AdvancedMediaPlayer object to play the desired format.

The AudioPlayer uses the adapter class MediaAdapter to pass the desired audio type without knowing the actual class that can play the audio in the desired format. AdapterPatternDemo, our demo class uses the AudioPlayer class to play various formats.

Step 1

Create interfaces for media players and more advanced media players.

public interface MediaPlayer {
   public void play(String audioType, String fileName);
}
Copy the code
public interface AdvancedMediaPlayer { 
   public void playVlc(String fileName);
   public void playMp4(String fileName);
}
Copy the code

Step 2

Create an entity class that implements the AdvancedMediaPlayer interface.

public class VlcPlayer implements AdvancedMediaPlayer{ @Override public void playVlc(String fileName) { System.out.println("Playing vlc file. Name: "+ fileName); } @override public void playMp4(String fileName) {// do nothing}Copy the code
Public class implements AdvancedMediaPlayer{@override public void playVlc(String fileName) {// implements AdvancedMediaPlayer; @Override public void playMp4(String fileName) { System.out.println("Playing mp4 file. Name: "+ fileName); }}Copy the code

Step 3

Create an adapter class that implements the MediaPlayer interface.

public class MediaAdapter implements MediaPlayer { AdvancedMediaPlayer advancedMusicPlayer; public MediaAdapter(String audioType){ if(audioType.equalsIgnoreCase("vlc") ){ advancedMusicPlayer = new VlcPlayer(); } else if (audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer = new Mp4Player(); } } @Override public void play(String audioType, String fileName) { if(audioType.equalsIgnoreCase("vlc")){ advancedMusicPlayer.playVlc(fileName); }else if(audioType.equalsIgnoreCase("mp4")){ advancedMusicPlayer.playMp4(fileName); }}}Copy the code

Step 4

Create an entity class that implements the MediaPlayer interface.

public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) {/ / play mp3 music files built-in support the if (audioType. EqualsIgnoreCase (" mp3 ")) {System. Out. Println (" Playing mp3 file. Name:  "+ fileName); } / / mediaAdapter provides play other file format support else if (audioType. EqualsIgnoreCase (VLC) | | audioType. EqualsIgnoreCase (" mp4 ")) { mediaAdapter = new MediaAdapter(audioType); mediaAdapter.play(audioType, fileName); } else{ System.out.println("Invalid media. "+ audioType + " format not supported"); }}}Copy the code

Step 5

Use AudioPlayer to play different types of audio formats.

public class AdapterPatternDemo { public static void main(String[] args) { AudioPlayer audioPlayer = new AudioPlayer(); audioPlayer.play("mp3", "beyond the horizon.mp3"); audioPlayer.play("mp4", "alone.mp4"); audioPlayer.play("vlc", "far far away.vlc"); audioPlayer.play("avi", "mind me.avi"); }}Copy the code

Step 6

Execute the program and output the result:

Playing mp3 file. Name: beyond the horizon.mp3
Playing mp4 file. Name: alone.mp4
Playing vlc file. Name: far far away.vlc
Invalid media. avi format not supported
Copy the code