java springboot 开发设计模式策略模式不同支付厂商接口
·
package com.tigshop.service.paytype;
import java.math.BigDecimal;
/**
* 1. 定义策略接口
*/
public interface PaymentTypeStrategy {
void pay(BigDecimal amount);
}
package com.tigshop.service.paytype;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
/**
* 2. 实现多种策略-微信
*/
@Component("wechatPay") // map 注入时使用的名称 注意:很重要
public class WechatPayStrategy implements PaymentTypeStrategy{
@Override
public void pay(BigDecimal amount) {
System.out.println("wechat支付");
}
}
package com.tigshop.service.paytype;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
/**
* 2. 实现多种策略-支付宝
*/
@Component("alipay") // map 注入时使用的名称 注意:很重要
public class AlipayStrategy implements PaymentTypeStrategy{
@Override
public void pay(BigDecimal amount) {
System.out.println("支付宝支付");
}
}
package com.tigshop.service.paytype;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.Map;
/**
* 3. 使用策略上下文
*/
@Service
public class PaymentTypeService {
// 注入所有实现,Map的key是Bean的名字,value是策略某一个支付实现类
@Autowired
private Map<String, PaymentTypeStrategy> strategyMap;
public void pay(String channel, BigDecimal amount) {
PaymentTypeStrategy strategy = strategyMap.get(channel);
if (strategy != null) {
strategy.pay(amount);
} else {
throw new IllegalArgumentException("Unsupported channel");
}
}
}
/**
* 支付控制器
*
* @author kidd
* @create 2025/7/7
*/
@Tag(name = "支付控制器", description = "支付控制器功能")
@RequiredArgsConstructor
@RestController
@RequestMapping("/adminapi/pay")
public class OrderController {
@Autowired
private PaymentTypeService paymentTypeService;
@GetMapping("/pay")
@Operation(summary = "不同支付厂商接口")
public OrderVO pay() {
paymentTypeService.pay("wechatPay", BigDecimal.ZERO);
paymentTypeService.pay("alipay", BigDecimal.ZERO);
return orderService.detail(id);
}
}
/**
* 构造函数注入策略类
applicationContext.getBeansOfType(ExpressStrategy.class); 防止空指针注入失败
**/
@Component
public class ExpressStrategyFactory implements ApplicationContextAware {
private Map<ExpressCompanyEnum, ExpressStrategy> strategyMap;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
// 获取所有ExpressStrategy的实现类
Map<String, ExpressStrategy> beans = applicationContext.getBeansOfType(ExpressStrategy.class);
// 构建快递公司到策略的映射
strategyMap = new HashMap<>();
for (ExpressStrategy strategy : beans.values()) {
strategyMap.put(strategy.getCompany(), strategy);
}
}
}
更多推荐
所有评论(0)