适配器模式

概念

  适配器模式是一种结构性模式,一般用于不兼容的情况出现时,比如笔记本电脑的电源适配器,就是转换电压的。代码同理,它结合了多个独立接口的功能。

角色

目标抽象类接口:定义所需的方法。
适配器类:实现了目标抽象类接口。
适配者类:包含目标类所需要使用的方法。

举个例子

  假如我们现在有两个类,一个类用来实现视频播放的(avi、mp4),一个类用来实现音频播放的,如mp3。假设我们现在有一个需求,需要实现一个能同时播放视频和音频的播放器,但我们又不知道这两个类的源码,这个时候就可以用适配器模式来实现了。

目标抽象类接口
/**
 * 需求接口,需要实现的功能
 *
 */
public interface Player {

	public void play(String filePath);
	
}
适配者类

视频播放器接口及其实现类

public interface VideoPlayer {
	
	public void playMp4(String filePath);
	
	public void playAVI(String filePath);
	
}
public class Mp4Player implements VideoPlayer{

	@Override
	public void playMp4(String filePath) {
		System.out.println("Play mp4 from "+filePath);
	}

	@Override
	public void playAVI(String filePath) {
		System.out.println("do nothing");
	}
	
}

public class AVIPlayer implements VideoPlayer {

	@Override
	public void playMp4(String filePath) {
		System.out.println("do nothing");
	}

	@Override
	public void playAVI(String filePath) {
		System.out.println("Play avi from " + filePath);
	}

}

音频播放器

public interface MusicPlayer {
	
	public void playMp3(String filePath);
}
public class Mp3Player implements MusicPlayer {

	@Override
	public void playMp3(String filePath) {
		System.out.println("Music play from " + filePath);
	}

}
适配器类

  这里顺带说一下,适配器分为两种,一种是对象适配器,就是我下面写的这种,还有一种叫类适配器,就是用一个adapter类去继承上面的MusicPlayer和VideoPlayer接口,这样也看出了类适配器的缺点,就是如果上面不是接口而是抽象类的话,就不能实现了。

public class ObjectAdapter implements Player {

	private Mp3Player mp3;
	private Mp4Player mp4;
	private AVIPlayer avi;
	
	public ObjectAdapter() {
		mp3 = new Mp3Player();
		mp4 = new Mp4Player();
		avi = new AVIPlayer();
	}
	
	private void playMp4(String filePath) {
		mp4.playMp4(filePath);
	}

	private void playAVI(String filePath) {
		avi.playAVI(filePath);
	}

	private void playMp3(String filePath) {
		mp3.playMp3(filePath);
	}

	@Override
	public void play(String filePath) {
		if(filePath.endsWith(".mp3")){
			playMp3(filePath);
		}else if(filePath.endsWith(".mp4")){
			playMp4(filePath);
		}else if(filePath.endsWith("avi")){
			playAVI(filePath);
		}else{
			System.out.println("不支持的格式");
		}
	}
	
}
客户端测试类
public class AdapterClient {
	public static void main(String[] args) {
		
		String aviPath = "data/data/vidio/123.avi";
		String mp4Path = "data/data/vidio/123.mp4";
		String mp3Path = "data/data/vidio/123.mp3";
		
		ObjectAdapter adapter = new ObjectAdapter();
		adapter.play(aviPath);
		adapter.play(mp3Path);
		adapter.play(mp4Path);
	}
}

结果

The End

适配器模式主要解决,要将一些"现存的对象"放到新的环境中,而新环境要求的接口是现对象不能满足的情况。
优点: 可以让任何两个没有关联的类一起运行、提高了类的复用。
缺点: 过多地使用适配器,会让系统非常零乱,不易整体进行把握。比如,明明看到调用的是 A 接口,其实内部被适配成了 B 接口的实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值