将一个类的接口转换成客户希望的另外一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。——Gang of Four
适配器模式的定义
适配器模式的定义是,Convert the interface of a class into another interface clients expect,将某个类的接口转换为接口客户所需的类型。换句话说,适配器模式解决的问题是,使得原本由于接口不兼容而不能一起工作、不能统一管理的那些类可以在一起工作、可以进行统一管理。
适配器模式使用
java适配器模式有两种,类适配器和对象适配器
. 角色
- 目标接口:Target,该角色把其他类转换为我们期望的接口
- 被适配者: Adaptee 原有的接口,也是希望被改变的接口
- 适配器: Adapter, 将被适配者和目标接口组合到一起的类
(1)类适配器demo
**类适配器主要是使用继承的方式连接两个接口。**在java中实现不了,需要多重继承才能实现,当然,如果我们变通一下,目标对象是接口就行了。
我们假设对接接口A和接口B。
先写接口B
public interface MP4{
void play();
}
接口B的实现类
public class ExpensiveMP4 implement MP4{
public void play(){
// todo
}
}
接口A
public interface Player{
void action();
}
假如你的工程中有这几个类,接着Player用户想要通过调用action方法来使用MP4。
然后我们采用,类适配器的方法。
public class ExpensiveAdapter extends ExpensiveMP4 implement Player{
public void action(){
play();
}
}
对于类适配器感觉用起来总不是很顺手。而且在java中,尽量少用继承,多用组合。
(2)对象适配器demo
这里的对象适配器用的是“组合”的方式。
这时候我们使用对象适配器的话可以这样写。
public class PlayerAdapter implement Player{
public ExpensiveMP4 expensiveMP4;
public PlayerAdapter (){
this.expensiveMP4 = new ExpensiveMP4();
}
public void action(){
if(expensiveMP4 != null){
expensiveMP4 .play();
}
}
}
然后稍微升级了一下。
public class PlayerAdapter implement Player{
public ExpensiveMP4 expensiveMP4;
public PlayerAdapter (ExpensiveMP4 expensiveMP4){
this.expensiveMP4 = expensiveMP4;
}
public void action(){
if(expensiveMP4 != null){
expensiveMP4 .play();
}
}
}
继续升级。
public class PlayerAdapter implement Player{
public MP4 mp4;
public PlayerAdapter (MP4 mp4){
this.mp4 = mp4;
}
public void action(){
if(mp4!= null){
mp4.play();
}
}
}
本文主要介绍了两种适配器模式,本质上是现有的不兼容的接口转换为需要的接口。
类适配器模式,以继承现有类的方式转换。
对象适配器模式,以聚合对象实例的方式转换。
类适配器和对象适配器的选择
- 从实现上:类适配器使用对象继承的方式,属于静态的定义方式。对象适配器使用对象组合的方式,属于动态组合的方式;
- 从工作模式上:类适配器直接继承了 Adaptee,使得适配器不能和 Adaptee 的子类一起工作。对象适配器允许一个 Adapter和多个 Adaptee,包括 Adaptee 和它所有的子类一起工作;
- 从定义角度:类适配器可以重定义 Adaptee 的部分行为,相当于子类覆盖父类的部分实现方法。对象适配器要重定义 Adaptee很困难;
- 从开发角度:类适配器仅仅引入了一个对象,并不需要额外的引用来间接得到 Adaptee。对象适配器需要额外的引用来间接得到Adaptee。