策略模式+工厂模式
public interface PaymentService {
void processPayment(BigDecimal amount);
}
@Service("ALIPAY")
public class AlipayService implements PaymentService {
@Override
public void processPayment(BigDecimal amount) {
System.out.println("支付宝支付: " + amount);
}
}
@Service("WECHAT")
public class WechatPayService implements PaymentService {
@Override
public void processPayment(BigDecimal amount) {
System.out.println("微信支付: " + amount);
}
}
@Component
public class PaymentServiceFactory {
private final Map<String, PaymentService> paymentServices;
// 自动注入所有 PaymentService 实现类
@Autowired
public PaymentServiceFactory(Map<String, PaymentService> paymentServices) {
this.paymentServices = paymentServices;
}
// 根据 type 获取对应的 Service
public PaymentService getService(String type) {
PaymentService service = paymentServices.get(type);
if (service == null) {
throw new IllegalArgumentException("无效支付类型: " + type);
}
return service;
}
}
@RestController
public class PaymentController {
@Autowired
private PaymentServiceFactory paymentServiceFactory;
@PostMapping("/pay")
public String pay(@RequestParam String type, @RequestParam BigDecimal amount) {
PaymentService service = paymentServiceFactory.getService(type);
service.processPayment(amount);
return "支付成功";
}
}
——————————————————————————————————————————————————
自定义注解 + 动态映射
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface PaymentType {
String value();
}
@Service
@PaymentType("ALIPAY")
public class AlipayService implements PaymentService {
@Override
public void processPayment(BigDecimal amount) {
System.out.println("支付宝支付: " + amount);
}
}
@Service
@PaymentType("WECHAT")
public class WechatPayService implements PaymentService {
@Override
public void processPayment(BigDecimal amount) {
System.out.println("微信支付: " + amount);
}
}
@Component
public class PaymentServiceFactory {
private final Map<String, PaymentService> paymentServices = new HashMap<>();
// 初始化时扫描所有带有 @PaymentType 注解的 Bean
@Autowired
public void initPaymentServices(List<PaymentService> services) {
for (PaymentService service : services) {
PaymentType annotation = service.getClass().getAnnotation(PaymentType.class);
if (annotation != null) {
paymentServices.put(annotation.value(), service);
}
}
}
public PaymentService getService(String type) {
PaymentService service = paymentServices.get(type);
if (service == null) {
throw new IllegalArgumentException("无效支付类型: " + type);
}
return service;
}
}
}
@RestController
public class PaymentController {
@Autowired
private PaymentServiceFactory paymentServiceFactory; // 注入工厂类:ml-citation{ref="4" data="citationList"}
@PostMapping("/pay")
public ResponseEntity<?> processPayment(@RequestParam String type, @RequestParam BigDecimal amount) {
// 根据 type 获取具体 Service 实现类
PaymentService service = paymentServiceFactory.getService(type);
service.processPayment(amount);
return ResponseEntity.ok("支付成功");
}
}
网友评论