适配器模式
适配器模式
核心
- 是有一个第三方的实现类,不能修改
- 需要外部包一层,起名Adapter结尾,并实现相关的特定业务接口
- 内部通过不能修改的第三方实现类去执行某些动作,完成业务功能
- 相当于是面向对象思想里封装的应用实现
2个接口,普通播放器,高级播放器
普通播放器 MediaPlayer
public interface MediaPlayer {
void play(String audioType, String fileName);
}
高级播放器 AdvancedMediaPlayer
public interface AdvancedMediaPlayer {
void playVlc(String fileName);
void playMp4(String fileName)
}
vlc播放器实现
public class VlcPlayer implements AdvancedMediaPlayer {
public void playVlc(String fileName){
System.out.println("vlc play :" + fileName);
}
public void playMp4(String fileName){
}
}
mp4播放器实现
public class Mp4Player implements AdvancedMediaPlayer {
public void playVlc(String fileName){
}
public void playMp4(String fileName){
System.out.println("mp4 play:" + fileName);
}
}
创建适配器,实现MediaPlayer
public MediaAdapter implements MediaPlayer {
AdvancedMediaPlayer advancedMediaPlayer;
public MediaAdapter(String audioType){
switch(audioType){
case "vlc":
advancedMediaPlayer = new VlcPlayer();
break;
case "mp4":
advancedMediaPlayer = new Mp4Player();
break;
}
}
public void play(String audioType, String fileName){
switch(audioType){
case "vlc":
advancedMediaPlayer.playVlc(fileName);
break;
case "mp4":
advancedMediaPlayer.playMp4(fileName);
break;
}
}
}
引用适配器,进行定义开发
public AudioPlayer implements MediaPlayer {
MediaAdapter mediaAdapter;
public void play(String audioType, String fileName){
switch(audioType){
case "mp3":
System.out.println("mp3 play:" + fileName);
break;
case "vlc":
mediaAdapter = new MediaAdapter("vlc");
mediaAdapter.play(audioType,fileName);
break;
case "mp4":
mediaAdapter = new MediaAdapter("mp4");
mediaAdapter.play(audioType,fileName);
break;
}
}
}
main函数测试
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");
}
}
适配器模式的代码样例
成员属性method和object对象,实例对象加方法,通过反射来进行执行
package com.jd.jmq.client.springboot.adaptor;
import com.jd.jmq.client.consumer.MessageListener;
import com.jd.jmq.common.message.Message;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
public class MessageListenerReflectAdapter implements MessageListener {
private final Method method;
private final Object instance;
public MessageListenerReflectAdapter(Object instance, Method method) {
this.instance = instance;
this.method = method;
this.method.setAccessible(true);
}
@Override
public void onMessage(List<Message> messages) {
try {
method.invoke(instance, messages);
} catch (InvocationTargetException e) {
if (e.getMessage() == null) {
throw new RuntimeException(e.getCause());
} else {
throw new RuntimeException(e);
}
} catch (Exception e) {
throw new RuntimeException("consume error", e);
}
}
}
原创:做时间的朋友