It is a structural pattern which organizes the classes and objects. Adapter Pattern is one of its types. This pattern makes the different interfaces to run together.
Java implementation:
It connects
the incompatible interfaces to work together. Let us create two interfaces.
- One is MPlayer (A media player). It has a play () method.
- Another interface is AMediaPlayer. It also has playMP4() method.
- A class (MP3Player) is created for MPlayer interface.
- ‘play()’ method is used to play Mp3 file.
- In the same way, another class(MP4Player) is created for AMediaPlayer interface.
- The ‘playMP4()’ definition is written.
- Adapter class is created with method. It connects both of the interfaces.
- A public class ‘MPPlay’ is developed with main() class.
- Objects are newly created for both classes. ‘play()’ and ‘playMP4()’ functions are called to display the result.
Program:
// interface 1
interface MPlayer {
void play(String
fname);
}
//class1 with method1
class MP3Player implements MPlayer {
public void
play(String fname) {
System.out.println("Playing MP3 file: " + fname);
}
}
//interface 2
interface AMediaPlayer {
void
playMP4(String fname);
}
//class 2 with method2
class MP4Player implements AMediaPlayer {
public void
playMP4(String fname) {
System.out.println("Playing MP4 file: " + fname);
}
}
//Adapter class definition
class MAdapter implements MPlayer {
private
AMediaPlayer aMediaPlayer;
MAdapter(String
format) {
if
(format.equalsIgnoreCase("mp4")) {
aMediaPlayer = new MP4Player();
}
}
public void
play(String fname) {
aMediaPlayer.playMP4(fname);
}
}
//main() function
public class MPPlay {
public static void
main(String[] args) {
MPlayer
player1 = new MP3Player();
player1.play("Manos Mars - The Tunning.mp3");
MPlayer
player2 = new MAdapter("mp4");
player2.play("j1.mp4");
}
}
The program is developed.
Output:
Compile and run the program to get the output.
C:\raji\blog>javac MPPlay.java
C:\raji\blog>java MPPlay
Playing MP3 file: Manos Mars - The Tunning.mp3
Playing MP4 file: j1.mp4
This is the java implementation of Adapter pattern. Hope,
this code will helpful to you. Keep Coding!!!
No comments:
Post a Comment