场景:策略模式实现不同类型的付款动作
package com.per.strategy;
/**
* @Title Strategy
* @Description TODO
* @Author Lee
* @Date 2024-01-20
*/
public interface PayStrategy {
/**
* 付款方式
*
* @return
*/
String getType();
/**
* 执行策略
*/
void process();
}
package com.per.strategy.service;
import com.per.strategy.PayStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @Title WeChatPayService
* @Description TODO
* @Author Lee
* @Date 2024-01-20
*/
@Component
@Slf4j
public class WeChatPayService implements PayStrategy {
@Override
public String getType() {
return "weChatPay";
}
@Override
public void process() {
log.info("微信付款100元");
}
}
package com.per.strategy.service;
import com.per.strategy.PayStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* @Title AliPayService
* @Description TODO
* @Author Lee
* @Date 2024-01-20
*/
@Component
@Slf4j
public class AliPayService implements PayStrategy {
@Override
public String getType() {
return "aliPay";
}
@Override
public void process() {
log.info("支付宝付款100元");
}
}
package com.per.strategy;
/**
* @Title PayStrategyHandler
* @Description TODO
* @Author Lee
* @Date 2024-01-20
*/
public interface PayStrategyHandler {
/**
* 执行策略
*
* @param type 付款方式
*/
void run(String type);
}
package com.per.strategy.config;
import com.per.strategy.PayStrategy;
import com.per.strategy.PayStrategyHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @Title PayStrategyConfig
* @Description TODO
* @Author Lee
* @Date 2024-01-20
*/
@Configuration
public class PayStrategyConfig {
/**
* 注册策略调度器
*
* @param payStrategies
* @return
*/
@Bean
public PayStrategyHandler handler(List<PayStrategy> payStrategies) {
Map<String, PayStrategy> strategyMaps = payStrategies.stream().collect(Collectors.toMap(PayStrategy::getType, item -> item));
// return new PayStrategyHandler() {
// @Override
// public void run(String type) {
// strategyMaps.get(type).process();
// }
// };
return type -> strategyMaps.get(type).process();
}
}
实际使用如下:
package com.per.controller;
import com.per.strategy.PayStrategyHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
/**
* @Title UserController
* @ProjectName spring-boot-demo
* @Description TODO
* @Author Lee
* @Date 2024-01-17
*/
@RestController
public class UserController {
@Autowired
private PayStrategyHandler handler;
/**
* 用户付款
*
* @return
*/
@RequestMapping(value = "strategy", method = RequestMethod.GET)
public String pay() {
String type = "weChatPay";
handler.run(type);
return "付款成功";
}
}