面试题答案
一键面试- 定义旧接口
OldService
:public interface OldService { void oldMethod(String param); }
- 定义新接口
NewService
:public interface NewService { void newMethod(int num); }
- 实现适配器类
OldToNewAdapter
:public class OldToNewAdapter implements NewService { private OldService oldService; public OldToNewAdapter(OldService oldService) { this.oldService = oldService; } @Override public void newMethod(int num) { // 将int转换为String String param = String.valueOf(num); oldService.oldMethod(param); } }
在实际使用中,可以这样:
public class Main {
public static void main(String[] args) {
OldService oldService = new OldServiceImpl();// 假设OldServiceImpl实现了OldService
NewService newService = new OldToNewAdapter(oldService);
newService.newMethod(123);
}
}
class OldServiceImpl implements OldService {
@Override
public void oldMethod(String param) {
System.out.println("Old method executed with param: " + param);
}
}
上述代码通过OldToNewAdapter
适配器类,将OldService
接口适配为NewService
接口,实现了接口转换。在OldToNewAdapter
中,将newMethod
的int
参数转换为String
参数,以适配oldMethod
的要求。