Adapter适配器模式
what
适配器模式是一种结构型设计模式, 创建一个适配器。 这是一个特殊的对象, 能够转换对象接口, 使其能与其他对象进行交互。
why
你可能根本没有程序的源代码, 从而无法对其本体程序库的现有代码进行修改。
structure

how
具体例子:
自己的支付服务(PaymentService),定义一个用于处理支付的方法。
一个第三方支付网关,它有一个与我们的接口不兼容的方法(executePayment)。
创建适配器类(PaymentGatewayAdapter),它实现了我们的支付服务接口,并接收一个第三方支付网关实例作为参数。适配器类内部通过调用第三方支付网关的方法来实现支付。
// 第三方支付网关接口
public interface ThirdPartyPaymentGateway {
void executePayment(int amount);
}
// 第三方支付网关的具体实现
public class PaymentGatewayImplementation {
public void makeTransaction(int paymentAmount) {
System.out.println("Executing payment with third-party payment gateway. Amount: $" + paymentAmount);
// 执行支付逻辑
}
}
// 自己的支付服务接口
public interface PaymentService {
void processPayment(int amount);
}
// 自己的支付服务实现
public class PaymentServiceImpl implements PaymentService {
public void processPayment(int amount) {
System.out.println("Processing payment internally. Amount: $" + amount);
// 执行自己的支付逻辑
}
}
// 适配器类
public class PaymentGatewayAdapter implements PaymentService {
private ThirdPartyPaymentGateway gateway; // 使用第三方支付网关接口
public PaymentGatewayAdapter(ThirdPartyPaymentGateway gateway) {
this.gateway = gateway;
}
public void processPayment(int amount) {
gateway.executePayment(amount); // 调用第三方支付网关的方法
}
}
// 在应用程序中使用适配器
public class Application {
public static void main(String[] args) {
PaymentService paymentService = new PaymentServiceImpl();
paymentService.processPayment(100);
ThirdPartyPaymentGateway paymentGateway = new PaymentGatewayImplementation();
PaymentService paymentAdapter = new PaymentGatewayAdapter(paymentGateway);
paymentAdapter.processPayment(200);
}
}
when
- 当你希望使用某个类, 但是其接口与其他代码不兼容时
- 有动机地修改一个正常运行的系统的接口,这时应该考虑使用适配器模式。
where
- jdbc
- Linux 上运行 windows 程序
P&Cs
P:
- 单一职责原则
- 开闭原则
C:
- 代码整体复杂度增加,有时直接更改服务类使其与其他代码兼容会更简单。
- 一个系统如果太多出现这种情况,无异于一场灾难。如果不是很有必要,可以不使用适配器,而是直接对系统进行重构。
summary
适配器模式不是在详细设计时添加的,而是解决正在服役的项目的问题。