适配器模式(Adapter Pattern)是一种结构型设计模式,它允许接口不兼容的类一起工作。适配器模式通过将类的接口转换为客户期望的另一个接口,使原本接口不兼容的类可以合作。
以下是一个简单的Java代码示例,演示如何使用适配器模式:
场景说明
假设你有一个MediaPlayer
接口,它可以播放音频文件。现在,你有一个更复杂的AdvancedMediaPlayer
接口,它可以播放音频和视频文件。你想让MediaPlayer
能够使用AdvancedMediaPlayer
来播放不同格式的文件,但不改变MediaPlayer
的接口。
代码实现
java">// 定义MediaPlayer接口
interface MediaPlayer {void play(String audioType, String fileName);
}// 定义AdvancedMediaPlayer接口
interface AdvancedMediaPlayer {void playVlc(String fileName);void playMp4(String fileName);
}// 实现AdvancedMediaPlayer接口的具体类
class VlcPlayer implements AdvancedMediaPlayer {public void playVlc(String fileName) {System.out.println("Playing vlc file. Name: " + fileName);}public void playMp4(String fileName) {// 什么也不做}
}class Mp4Player implements AdvancedMediaPlayer {public void playVlc(String fileName) {// 什么也不做}public void playMp4(String fileName) {System.out.println("Playing mp4 file. Name: " + fileName);}
}// 创建适配器类,实现MediaPlayer接口,并使用AdvancedMediaPlayer对象
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();}}@Overridepublic void play(String audioType, String fileName) {if (audioType.equalsIgnoreCase("vlc")) {advancedMusicPlayer.playVlc(fileName);} else if (audioType.equalsIgnoreCase("mp4")) {advancedMusicPlayer.playMp4(fileName);}}
}// 实现MediaPlayer接口的具体类
class AudioPlayer implements MediaPlayer {MediaAdapter mediaAdapter;@Overridepublic void play(String audioType, String fileName) {// 支持MP3播放if (audioType.equalsIgnoreCase("mp3")) {System.out.println("Playing mp3 file. Name: " + fileName);}// 使用适配器播放vlc和mp4文件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");}}
}// 测试代码
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");}
}
输出结果
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
代码解释
MediaPlayer
接口定义了播放媒体文件的方法play()
。AdvancedMediaPlayer
接口定义了播放特定格式文件的方法playVlc()
和playMp4()
。VlcPlayer
和Mp4Player
是AdvancedMediaPlayer
的具体实现类。MediaAdapter
类是适配器,它实现了MediaPlayer
接口,并将请求委托给合适的AdvancedMediaPlayer
对象。AudioPlayer
类是客户端,它可以使用MediaAdapter
来播放不同格式的文件。
这个例子展示了如何使用适配器模式来让不同接口的类可以协同工作,而无需修改它们的源代码。