MST

星途 面试题库

面试题:Java微服务架构中Java适配器模式接口转换的基本实现

请描述在Java微服务架构场景下,如何使用适配器模式进行接口转换。假设你有一个遗留系统接口OldService,其方法为`void oldMethod(String param)`,新的微服务需要的接口NewService要求`void newMethod(int num)`,请给出具体的适配器类实现代码。
14.9万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 定义旧接口OldService
    public interface OldService {
        void oldMethod(String param);
    }
    
  2. 定义新接口NewService
    public interface NewService {
        void newMethod(int num);
    }
    
  3. 实现适配器类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中,将newMethodint参数转换为String参数,以适配oldMethod的要求。