智能体插槽架构:面向AI工程化的可拔插能力设计
2026/10/22 22:07:32
适配器模式是一种结构型设计模式,它允许不兼容的接口一起工作。适配器模式充当两个不兼容接口之间的桥梁。
简单来说:适配器模式就像一个转换器,让不兼容的接口能够协同工作。
想象一下:
// 假设有一个第三方库,接口与我们系统不兼容ThirdPartyServiceservice=newThirdPartyService();service.doSomethingElse();// 接口不兼容,无法使用问题:
// 使用适配器Adapteradapter=newAdapter(newThirdPartyService());adapter.doSomething();// 通过适配器调用优势:
┌─────────────────────┐ │ Target │ 目标接口 ├─────────────────────┤ │ + request(): void │ └─────────────────────┘ ▲ │ 实现 │ ┌────────┴────────┐ │ Adapter │ 适配器 ├─────────────────┤ │ - adaptee: Adaptee│ │ + request(): void│ └────────┬────────┘ │ 组合 │ ┌────────┴────────┐ │ Adaptee │ 被适配者 ├─────────────────┤ │ + specificRequest(): void│ └─────────────────┘/** * 目标接口 */publicinterfaceTarget{/** * 请求方法 */voidrequest();}/** * 被适配者:拥有不兼容接口的类 */publicclassAdaptee{/** * 特定请求方法(与目标接口不兼容) */publicvoidspecificRequest(){System.out.println("被适配者执行特定请求");}}/** * 适配器:将目标接口转换为被适配者的接口 */publicclassAdapterimplementsTarget{privateAdapteeadaptee;publicAdapter(Adapteeadaptee){this.adaptee=adaptee;}@Overridepublicvoidrequest(){System.out.println("适配器转换请求...");adaptee.specificRequest();}}/** * 适配器模式测试类 * 演示如何使用适配器模式让不兼容的接口协同工作 */publicclassAdapterTest{publicstaticvoidmain(String[]args){System.out.println("=== 适配器模式测试 ===\n");// 创建被适配者Adapteeadaptee=newAdaptee();System.out.println("--- 直接调用被适配者(不兼容) ---");System.out.println("客户端无法直接使用被适配者的接口");System.out.println("\n--- 使用适配器 ---");// 创建适配器Targettarget=newAdapter(adaptee);// 客户端通过目标接口调用target.request();System.out.println("\n=== 实际应用场景示例:电源适配器 ===");System.out.println("场景:中国的电器(220V)要在美国使用(110V)");System.out.println("解决方案:使用电源适配器将110V转换为220V");System.out.println("\n=== 适配器模式的优势 ===");System.out.println("1. 接口兼容:让不兼容的接口能够协同工作");System.out.println("2. 无需修改:无需修改原有代码");System.out.println("3. 解耦合:降低系统与第三方库的耦合度");System.out.println("4. 灵活扩展:可以轻松添加新的适配器");}}⚠️ 适配器模式虽然有用,但要注意: