面试题答案
一键面试1. 定义目标接口
目标接口是项目中期望的接口规范。假设我们期望的功能是获取数据,定义如下:
public interface TargetInterface {
String getData();
}
2. 分析第三方库类
假设第三方库类 ThirdPartyClass
有一个 fetchData
方法,但返回值类型和方法名与目标接口不匹配:
public class ThirdPartyClass {
public int fetchData() {
// 实际业务逻辑,返回一个整数
return 42;
}
}
3. 创建适配器类
适配器类实现目标接口,并持有一个第三方库类的实例,在目标接口方法中调用第三方库类的方法进行适配:
public class Adapter implements TargetInterface {
private ThirdPartyClass thirdPartyClass;
public Adapter(ThirdPartyClass thirdPartyClass) {
this.thirdPartyClass = thirdPartyClass;
}
@Override
public String getData() {
int data = thirdPartyClass.fetchData();
return String.valueOf(data);
}
}
4. 使用适配器
在项目代码中使用适配器将第三方库类适配到目标接口:
public class Main {
public static void main(String[] args) {
ThirdPartyClass thirdPartyClass = new ThirdPartyClass();
TargetInterface target = new Adapter(thirdPartyClass);
String result = target.getData();
System.out.println(result);
}
}