The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Adapter example
By Guest on 18th February 2025 04:10:55 AM | Syntax: TEXT | Views: 2



New paste | Download | Show/Hide line no. | Copy text to clipboard
  1. // Target interface
  2. interface MediaPlayer {
  3.     void play(String audioType, String fileName);
  4. }
  5.  
  6. // Adaptee class
  7. class AdvancedMediaPlayer {
  8.     void playVlc(String fileName) {
  9.         System.out.println("Playing VLC file: " + fileName);
  10.     }
  11.  
  12.     void playMp4(String fileName) {
  13.         System.out.println("Playing MP4 file: " + fileName);
  14.     }
  15. }
  16.  
  17. // Adapter class
  18. class MediaAdapter implements MediaPlayer {
  19.     private final AdvancedMediaPlayer advancedMediaPlayer;
  20.  
  21.     public MediaAdapter(String audioType) {
  22.         if (audioType.equalsIgnoreCase("vlc")) {
  23.             this.advancedMediaPlayer = new AdvancedMediaPlayer();
  24.         } else if (audioType.equalsIgnoreCase("mp4")) {
  25.             this.advancedMediaPlayer = new AdvancedMediaPlayer();
  26.         } else {
  27.             this.advancedMediaPlayer = null; // No advanced player for unsupported formats
  28.         }
  29.     }
  30.  
  31.     @Override
  32.     public void play(String audioType, String fileName) {
  33.         if (audioType.equalsIgnoreCase("vlc")) {
  34.             advancedMediaPlayer.playVlc(fileName);
  35.         } else if (audioType.equalsIgnoreCase("mp4")) {
  36.             advancedMediaPlayer.playMp4(fileName);
  37.         }
  38.     }
  39. }
  40.  
  41. // Client class
  42. class AudioPlayer implements MediaPlayer {
  43.     private MediaAdapter mediaAdapter;
  44.  
  45.     @Override
  46.     public void play(String audioType, String fileName) {
  47.         if (audioType.equalsIgnoreCase("mp3")) {
  48.             System.out.println("Playing MP3 file: " + fileName);
  49.         } else if (audioType.equalsIgnoreCase("vlc") || audioType.equalsIgnoreCase("mp4")) {
  50.             mediaAdapter = new MediaAdapter(audioType);
  51.             mediaAdapter.play(audioType, fileName);
  52.         } else {
  53.             System.out.println("Invalid media format: " + audioType);
  54.         }
  55.     }
  56. }
  57.  
  58. // Main class to test the Adapter Design Pattern
  59. public class AdapterPatternExample {
  60.     public static void main(String[] args) {
  61.         AudioPlayer audioPlayer = new AudioPlayer();
  62.  
  63.         audioPlayer.play("mp3", "song.mp3");
  64.         audioPlayer.play("mp4", "video.mp4");
  65.         audioPlayer.play("vlc", "movie.vlc");
  66.         audioPlayer.play("avi", "unsupported.avi");
  67.     }
  68. }



  • Recent Pastes

Upload your own Photos at PasteNet Photos


Free Packet LLC
For all your hosting needs!