Java设计模式——适配器模式
Posted iceriver315
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java设计模式——适配器模式相关的知识,希望对你有一定的参考价值。
适配器模式充当两个不兼容接口之间的桥梁, 它属于结构模式。
它涉及一个单一的类,负责连接独立或不兼容的接口功能。比如读卡器,它充当存储卡和电脑之间的适配器。我们将存储卡插入读卡器并将读卡器插入电脑,这样就可以通过电脑读取存储卡内容。
下面进行演示说明。
需求:假设我们有一台MP3播放器,但我们又希望它能播放vlc和mp4文件。
步骤:
1、创建接口MediaPlayer(媒体播放),以及一个实现类AudioPlayer(音频播放)
2、创建另外一个接口AdvancedMediaPlayer(高级媒体播放器),以及它的实现类(VLCPlayer、Mp4Player)
3、我们想让 AudioPlayer也能播放vlc和mp4。创建一个适配器类MediaAdapter,它实现了MediaPlayer接口,并使用 AdvancedMediaPlayer对象来播放所需的格式。
4、AudioPlayer 使用适配器类 MediaAdapter,并将媒体文件传递给它,并不需知道实际文件类型。
1、创建接口MediaPlayer、AdvancedMediaPlayer
public interface MediaPlayer public void play(String audioType, String fileName); public interface AdvancedMediaPlayer public void playVlc(String fileName); public void playMp4(String fileName);
2、创建AdvancedMediaPlayer的实现类
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 public class Mp4Player implements AdvancedMediaPlayer @Override public void playVlc(String fileName) //do nothing @Override public void playMp4(String fileName) System.out.println("Playing mp4 file. Name: "+ fileName);
3、创建适配器类MediaAdapter,实现接口MediaPlayer
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);
4、创建AudioPlayer类,实现接口MediaPlayer
public class AudioPlayer implements MediaPlayer MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) //inbuilt support to play mp3 music files if(audioType.equalsIgnoreCase("mp3")) System.out.println("Playing mp3 file. Name: " + fileName); //mediaAdapter is providing support to play other file formats 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");
5、测试
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");
6、结果
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
以上是关于Java设计模式——适配器模式的主要内容,如果未能解决你的问题,请参考以下文章