将一个类的接口转换成客户希望的另外一个接口。 Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。 模式中的角色: 1. 需要适配的类(Adaptee):需要适配的类或适配者类。 2. 适配器(Adapter):通过包装一个需要适配的对象,把原接口转换成目标接口。 3. 目标接口(Target):客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口。 优点: 1. 可以让任何两个没有关联的类一起运行。 2. 提高了类的复用。 3. 增加了类的透明度。 4. 灵活性好。 缺点: 1. 过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是A接口,其实内部被适配成了B接口的实现,一个系统如果太多出现这种情况,无异于一场灾难。因此如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。 2. 由于JAVA至多继承一个类,所以至多只能适配一个适配者类,而且目标类必须是抽象类。
1. 适配器模式
package com.andrew.pattern0201.adapter.model01; public interface MediaPlayer { public void play(String audioType, String fileName); } package com.andrew.pattern0201.adapter.model01; public interface AdvancedMediaPlayer { public void playVlc(String fileName); public void playMp4(String fileName); }
package com.andrew.pattern0201.adapter.model01; 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) { } } package com.andrew.pattern0201.adapter.model01; public class Mp4Player implements AdvancedMediaPlayer { @Override public void playVlc(String fileName) { } @Override public void playMp4(String fileName) { System.out.println("Playing mp4 file. Name: "+ fileName); } } package com.andrew.pattern0201.adapter.model01; 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); } } }
package com.andrew.pattern0201.adapter.model01; public class AudioPlayer implements MediaPlayer { MediaAdapter mediaAdapter; @Override public void play(String audioType, String fileName) { if (audioType.equalsIgnoreCase("mp3")) { System.out.println("Playing mp3 file. Name: "+ fileName); } 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"); } } }
package com.andrew.pattern0201.adapter.model01; /** * 1. 适配器模式 * * @author andrew * @date 2018/07/18 */ public class AdapterClient { 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