适配器模式总的来说分为三种:类适配器,对象适配器,接口适配器。这里只总结两种也是因为类适配器很简单并且对象适配器就是在类适配器上做改造因此懂得了对象适配器,类适配器一想就明白。
适配器模式和生活中的充电线转换头很像,因此以此来当作例子会很容易明白。
适配器就相当于一根安卓线要通过转换头去给苹果手机充电。
接下来就是我自己手写的充电代码:
对象适配器:
/**
* @author Jay
* @date 2020/7/15 19:26
* @Description:
* 安卓线
*/
public class AndroidUSB {
public String ChargeAndroid(){
String ChargeLine="Andriod";
return ChargeLine;
}
}
/**
* @author Jay
* @date 2020/7/15 19:30
* @Description:
* iphone头定义为接口
*/
public interface IphoneHead {
String ChargeIphone();
}
/**
* @author Jay
* @date 2020/7/15 19:30
* @Description:
* 转换头
*/
public class USBAdapter extends AndroidUSB implements IphoneHead {
//定义一个为空的安卓USB对象
private AndroidUSB androidUSB;
//通过构造器注入,使得转换器中可以对安卓线进行转换,就像将安卓线插入转换头中
public USBAdapter(AndroidUSB androidUSB){
this.androidUSB=androidUSB;
}
@Override
public String ChargeIphone() {
String s =null;
//保证安卓线是好的
if (androidUSB!=null){
//转换过程
s=androidUSB.ChargeAndroid().replace("Andriod","Iphone");
}
//返回苹果头
return s;
}
}
接口适配器
修改增加了几个类和接口
/**
* @author Jay
* @date 2020/7/15 19:25
* @Description:
*/
public interface USB {
String ChargeIphone();
String ChargeHuawei();
}
/**
* @author Jay
* @date 2020/7/15 19:30
* @Description:
* 转换头
*/
public class USBAdapter implements USB {
//定义一个为空的安卓USB对象
public AndroidUSB androidUSB;
//通过构造器注入,使得转换器中可以对安卓线进行转换,就像将安卓线插入转换头中
public USBAdapter(AndroidUSB androidUSB){
this.androidUSB=androidUSB;
}
@Override
public String ChargeIphone() {
return androidUSB.ChargeAndroid();
}
@Override
public String ChargeHuawei() {
return androidUSB.ChargeAndroid();
}
}
/**
* @author Jay
* @date 2020/7/15 19:30
* @Description:
*/
public class IphoneHead extends USBAdapter {
public IphoneHead(AndroidUSB androidUSB) {
super(androidUSB);
}
public String ChargeIphone() {
String s =null;
//保证安卓线是好的
if (androidUSB!=null){
//转换过程
s=androidUSB.ChargeAndroid().replace("Andriod","Iphone");
}
//返回苹果头
return s;
}
}
/**
* @author Jay
* @date 2020/7/15 20:34
* @Description:
*/
public class HuaweiHead extends USBAdapter{
public HuaweiHead(AndroidUSB androidUSB) {
super(androidUSB);
}
public String ChargeHuawei() {
String s =null;
//保证安卓线是好的
if (androidUSB!=null){
//转换过程
s=androidUSB.ChargeAndroid().replace("Andriod","Huawei");
}
//返回苹果头
return s;
}
}
适配器模式应用场景
类适配器与对象适配器的使用场景一致,仅仅是实现手段稍有区别,二者主要用于如下场景:
(1)想要使用一个已经存在的类,但是它却不符合现有的接口规范,导致无法直接去访问,这时创建一个适配器就能间接去访问这个类中的方法。
(2)我们有一个类,想将其设计为可重用的类(可被多处访问),我们可以创建适配器来将这个类来适配其他没有提供合适接口的类。
以上两个场景其实就是从两个角度来描述一类问题,那就是要访问的方法不在合适的接口里,一个从接口出发(被访问),一个从访问出发(主动访问)。
接口适配器使用场景:
(1)想要使用接口中的某个或某些方法,但是接口中有太多方法,我们要使用时必须实现接口并实现其中的所有方法,可以使用抽象类来实现接口,并不对方法进行实现(仅置空),然后我们再继承这个抽象类来通过重写想用的方法的方式来实现。这个抽象类就是适配器。
总结:被适配类(Source)的存在形式决定了适配器的名字。类适配器就是继承Source类,对象适配器就是持有Source类对象,接口适配器是基于对象适配器的改进。如果有90%的把握确定需要适配出来的接口只有一种或两种不建议用这个方法了,建议使用对象适配器,如果将来需要适配出来的接口更多,那么用接口适配器,选择合适的就好了。