概述
定义:已经存在的类,它的方法和需求不匹配时(方法结果相同或类似),将适配的类的API转换为目标类的API
优点:提高类的复用性;目标类和程序解耦,提高程序扩展性
缺点:增加系统代码可读的难度;适配器编写过程需要全面考虑
类型:结构型
类适配器
Target期待调用Request方法,而Adaptee没有(这就是所谓的不兼容了),为使Target能够使用Adaptee类的SpecificRequest方法,故提供一个中间环节Adapter类(继承Adaptee&实现Target接口),把Adaptee的API与Target的API衔接起来(适配)
实例分析
#Adaptee
public class Adaptee {
public void SpecificRequest(){
System.out.println("被适配的方法");
}
}
#Target
public interface Target {
void Request();
}
#Adapter
public class Adapter extends Adaptee implements Target {
@Override
public void Request() {
SpecificRequest();
System.out.println("被适配后的方法");
}
public static void main(String[] args) {
Target target = new Adapter();
target.Request();
}
}
对象适配器模式
与类的适配器模式相同,对象的适配器模式也是把适配的类的API转换为目标类的API。与类适配器模式不同,对象适配器模式采用组合的关系实现适配。
#Target类
//创建Target接口
public interface Target {
void Request();
}
#被适配器类
public class Adaptee {
public void SpecificRequest(){
System.out.println("被适配的方法");
}
}
#适配器类
public class Adapter implements Target{
//通过组合的方式实现注入
private Adaptee adaptee;
public Adapter(Adaptee adaptee){
this.adaptee=adaptee;
}
@Override
public void Request() {
adaptee.SpecificRequest();
System.out.println("被适配后的方法");
}
}