The Adapter Pattern refers to the process of transforming the interface of a class into a different interface that is desired by a client.
Put simply, the goal is to create an interface that meets the client's specifications while utilizing a class with a distinct interface. The Adapter Pattern is alternatively referred to as the Wrapper Pattern.
The advantage of the Adapter Pattern is its ability to allow incompatible classes to work together by converting the interface of one class into another interface that clients expect.
It facilitates the interaction between two or more objects that were previously incompatible.
It enables the reuse of pre-existing functionality.
The Adapter pattern is used
- when an object has to make use of an existing class that has an interface that is not compatible.
- when you need to design a reusable class that can work together with classes that have incompatible interfaces.
- If you need to develop a reusable class that can work together with classes that have incompatible interfaces.
Source code of AudioPlayerIntf.java
package com.t4b.test.java.dp.sp.ap;
interface AudioPlayerIntf {
public void playAudio(String fileName);
}
Source code of AudioPlayer.java
package com.t4b.test.java.dp.sp.ap;
class AudioPlayer implements AudioPlayerIntf {
@Override
public void playAudio(String fileName) {
System.out.println("Playing. Name: " + fileName);
}
}
Source code of VideoPlayerIntf.java
package com.t4b.test.java.dp.sp.ap;
interface VideoPlayerIntf {
public void playVideo(String fileName);
}
Source code of VideoPlayer.java
package com.t4b.test.java.dp.sp.ap;
class VideoPlayer implements VideoPlayerIntf {
@Override
public void playVideo(String fileName) {
System.out.println("Playing. Name: " + fileName);
}
}
Source code of MediaPlayerIntf.java
package com.t4b.test.java.dp.sp.ap;
interface MediaPlayerIntf {
public void play(String type, String fileName);
}
Source code of MediaPlayer.java
package com.t4b.test.java.dp.sp.ap;
class MediaPlayer implements MediaPlayerIntf {
AudioPlayerIntf audioPlayer = new AudioPlayer();
VideoPlayerIntf videoPlayer = new VideoPlayer();
public MediaPlayer() {
}
@Override
public void play(String audioType, String fileName) {
if (audioType.equalsIgnoreCase("avi")) {
videoPlayer.playVideo(fileName);
} else if (audioType.equalsIgnoreCase("mp3")) {
audioPlayer.playAudio(fileName);
}
}
}
Source code of TestMain.java
package com.t4b.test.java.dp.sp.ap;
public class TestMain {
public static void main(String[] args) {
MediaPlayer myPlayer = new MediaPlayer();
myPlayer.play("mp3", "h.mp3");
myPlayer.play("avi", "me.avi");
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.