什么是适配器模式?
适配器模式是一种结构型设计模式,它允许不兼容的接口协同工作。该模式将一个类的接口转换成客户端期望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以协同工作。
适配器模式包含以下角色:
- 目标接口(Target):客户端期望的接口
- 适配者类(Adaptee):需要被适配的类,具有不兼容的接口
- 适配器类(Adapter):实现目标接口,并持有适配者类的引用,负责协调两者之间的接口转换
适配器模式的优缺点
优点:
- 单一职责原则:可以将接口或数据转换代码从主要业务逻辑中分离
- 开闭原则:可以在不修改现有代码的情况下添加新的适配器
- 提高代码复用性:可以复用现有的不兼容类
- 灵活性高:可以为同一个适配者提供多个不同的适配器
缺点:
- 代码复杂度增加:引入额外的类,使代码结构变得复杂
- 性能略有损失:适配过程中可能需要进行额外的对象创建和方法调用
- 难以维护:过多的适配器会增加系统的维护成本
什么场景下使用适配器模式
- 系统需要使用现有的类,但其接口不符合需求
- 想要创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类协同工作
- 需要使用一些已经存在的子类,但不可能对每一个都进行子类化以匹配它们的接口,对象适配器可以适配它的父类接口
- 在调用第三方库或遗留代码时,接口不匹配的情况
代码举例
// 目标接口 - 客户端期望的统一支付接口
interface PaymentProcessor {boolean pay(String account, double amount);String getPaymentStatus(String transactionId);
}// 适配者类 - 已有的支付宝支付系统
class AlipaySystem {public boolean makePayment(String userId, double money) {System.out.println("使用支付宝支付 " + money + " 元");return true;}public String checkStatus(String orderId) {return "支付宝支付成功";}
}// 适配者类 - 已有的微信支付系统
class WeChatPaySystem {public boolean processPayment(String userAccount, double fee) {System.out.println("使用微信支付 " + fee + " 元");return true;}public String queryStatus(String tradeNo) {return "微信支付成功";}
}// 适配器类 - 支付宝适配器
class AlipayAdapter implements PaymentProcessor {private AlipaySystem alipay;public AlipayAdapter(AlipaySystem alipay) {this.alipay = alipay;}@Overridepublic boolean pay(String account, double amount) {return alipay.makePayment(account, amount);}@Overridepublic String getPaymentStatus(String transactionId) {return alipay.checkStatus(transactionId);}
}// 适配器类 - 微信支付适配器
class WeChatPayAdapter implements PaymentProcessor {private WeChatPaySystem wechatPay;public WeChatPayAdapter(WeChatPaySystem wechatPay) {this.wechatPay = wechatPay;}@Overridepublic boolean pay(String account, double amount) {return wechatPay.processPayment(account, amount);}@Overridepublic String getPaymentStatus(String transactionId) {return wechatPay.queryStatus(transactionId);}
}// 客户端代码
public class PaymentClient {public static void main(String[] args) {// 使用支付宝支付PaymentProcessor alipayProcessor = new AlipayAdapter(new AlipaySystem());alipayProcessor.pay("user123", 100.0);System.out.println(alipayProcessor.getPaymentStatus("txn001"));// 使用微信支付PaymentProcessor wechatProcessor = new WeChatPayAdapter(new WeChatPaySystem());wechatProcessor.pay("user456", 200.0);System.out.println(wechatProcessor.getPaymentStatus("txn002"));}
}