在六边形架构中,如何处理多个外部系统的集成?请举例说明。
在六边形架构中,处理多个外部系统的集成主要依赖于适配器模式。该模式将外部系统的交互逻辑封装在一层中,确保核心业务逻辑免受外部变动的影响。适配器实现端口定义的接口,每个端口定义了与外部系统交互的抽象方法。通过这种方式,可以灵活地更换或添加新的外部系统,而无需更改内部业务逻辑。
示例
假设我们正在开发一个电子商务平台,平台需要与以下两个外部系统集成:
- 支付系统:负责处理订单支付。
- 库存管理系统:负责更新商品库存。
1. 端口定义
首先,定义两个端口,分别对应上述两个外部系统。端口定义了与外部系统交互的抽象方法:
public interface PaymentPort {
PaymentResult processPayment(Order order);
}
public interface InventoryPort {
void updateStock(Product product, int quantity);
}
2. 适配器实现
接下来,为每个外部系统实现一个适配器,适配器实现了端口定义的接口,并封装了与外部系统的实际交互逻辑。
public class PaymentAdapter implements PaymentPort {
private final PaymentService paymentService;
public PaymentAdapter(PaymentService paymentService) {
this.paymentService = paymentService;
}
@Override
public PaymentResult processPayment(Order order) {
// 调用支付系统的API处理支付
return paymentService.processPayment(order);
}
}
public class InventoryAdapter implements InventoryPort {
private final InventoryService inventoryService;
public InventoryAdapter(InventoryService inventoryService) {
this.inventoryService = inventoryService;
}
@Override
public void updateStock(Product product, int quantity) {
// 调用库存管理系统的API更新库存
inventoryService.updateStock(product, quantity);
}
}
3. 业务逻辑
核心业务逻辑中,通过依赖注入的方式使用这些端口,确保了业务逻辑与外部系统的解耦。
public class OrderService {
private final PaymentPort paymentPort;
private final InventoryPort inventoryPort;
public OrderService(PaymentPort paymentPort, InventoryPort inventoryPort) {
this.paymentPort = paymentPort;
this.inventoryPort = inventoryPort;
}
public void placeOrder(Order order) {
// 1. 处理支付
PaymentResult paymentResult = paymentPort.processPayment(order);
if (!paymentResult.isSuccess()) {
throw new PaymentFailedException(paymentResult.getMessage());
}
// 2. 更新库存
for (OrderItem item : order.getItems()) {
inventoryPort.updateStock(item.getProduct(), -item.getQuantity());
}
// 3. 其他业务逻辑
// ...
}
}
通过这种方式,即使外部系统发生变化,如更换支付供应商或库存管理系统,我们只需要修改相应的适配器,而无需更改业务逻辑代码。这提高了系统的可维护性和扩展性。