适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。
这种模式涉及到一个单一的类,该类负责加入独立的或不兼容的接口功能。
实例:MP3播放器可以播放MP3格式的文件,MP4播放器可以播放MP4格式的文件,我们想实现MP4播放器既可以播放MP4也可以播放MP3格式文件。通过adapter类,实现这一功能。
package com.wms.adapterPattern;
/**
* @date:2018/11/14
* @desc:
*/
public interface Players {
void play(String type, String name);
}
package com.wms.adapterPattern;
/**
* @date:2018/11/14
* @desc:
*/
public class Mp3Player implements Players {
public void play(String type, String name) {
if (type.equals("mp3"))
System.out.println("play mp3....");
else System.out.println("not support" + name);
}
}
package com.wms.adapterPattern;
/**
* @date:2018/11/14
* @desc: 适配器
*/
public class Adapter extends Mp3Player {
private Mp3Player mp3Player;
public Adapter(Mp3Player mp3Player) {
this.mp3Player = mp3Player;
}
public void play(String type, String name) {
if (type.equals("mp3"))
this.mp3Player.play(type, name);
}
}
package com.wms.adapterPattern;
import com.sun.xml.internal.bind.v2.model.core.ID;
/**
* @date:2018/11/14
* @desc:
*/
public class Mp4Player implements Players {
private Adapter adapter;
public Mp4Player(Adapter adapter) {
this.adapter = adapter;
}
public void play(String type, String name) {
if (type.equals("mp4")) {
System.out.println("play mp4....");
} else if (type.equals("mp3")) {
this.adapter.play(type,name);
}
}
}
package com.wms.adapterPattern;
/**
* @date:2018/11/14
* @desc: 需求:让MP4可以播放MP3
*/
public class AdapterDemo {
public static void main(String[] args) {
Adapter adapter = new Adapter(new Mp3Player());
Mp4Player mp4Player = new Mp4Player(adapter);
mp4Player.play("mp3", "music");
}
}
实现MP4播放器可以播放MP3格式的文件。