定义
将一个接口转换成用户希望的另一个接口,适配器模式使接口不兼容的那些类可以一起工作,其别名为包装器(wrapper)
一,类适配器
类的适配器模式把适配的类的API转换成目标类的API
Adapter继承自Adaptee
Adaptee
public class Adaptee {
public void method1(){
Log.e("TAG", "method1: " );
}
}
Target
public interface Target {
void method1();
void method2();
}
Adapter
public class Adapter extends Adaptee implements Target {
@Override
public void method2() {
Log.e("TAG","method2: ");
}
}
Main
Adapter adapter = new Adapter();
adapter.method1();
adapter.method2();
2020-03-30 17:17:56.146 14234-14234/com.zhangyu.myapplication E/TAG: method1:
2020-03-30 17:17:56.146 14234-14234/com.zhangyu.myapplication E/TAG: method2:
二,对象适配器
与类的适配器模式一样,对象适配器模式把被适配类的API转换成目标类的API,与类的适配器模式不同的是,对象的适配器模式不是使用继承关系连接到Adaptee类,而是使用委派关系连接Adaptee。
Adapter2
public class Adapter2 implements Target {
private Adaptee adaptee;
public Adapter2(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void method1() {
adaptee.method1();
}
@Override
public void method2() {
Log.e("TAG", "method2: ");
}
}
Main
Adapter2 adapter2 = new Adapter2(new Adaptee());
adapter2.method1();
adapter2.method2();
2020-03-30 17:27:52.099 15018-15018/com.zhangyu.myapplication E/TAG: method1:
2020-03-30 17:27:52.099 15018-15018/com.zhangyu.myapplication E/TAG: method2: