今天在写策略模式,一开始打算使用反射的方式获取策略类,突然想到可不可以借用spring的ioc,使用自动注入的方式.
策略接口
/**
* 提现策略接口
*
* @since 2021-11-11 10:03
*/
public interface WithdrawStrategy {
/**
* 获取当前提现类型标识
*
* @return 提现类型标识
* @since 2021/11/11 10:36
*/
int getType();
/**
* 订单结算
*
* @param orderIds 订单id
* @since 2021/11/11 10:09
*/
void settlement(String[] orderIds);
}
策略类
/**
* 支付宝结算
*
* @since 2021-11-11 10:10
*/
@Component
public class AlipayPaymentStrategy implements WithdrawStrategy {
/**
* 获取当前提现类型标识
*
* @return 提现类型标识
* @since 2021/11/11 10:36
*/
@Override
public int getType() {
return 2;
}
/**
* 订单结算
*
* @param orderIds 订单id
* @since 2021/11/11 10:09
*/
@Override
public void settlement(String[] orderIds) {
//todo: 进行结算
}
}
一共有三个策略类 就不一一展示了
策略上下文
/**
* 提现上下文
*
* @since 2021-11-11 10:13
*/
@Component
public class WithdrawContext {
/**
* 注入到策略接口集合
*/
@Resource
private List<WithdrawStrategy> strategy;
private static Map<Integer, WithdrawStrategy> strategyMap;
/**
*将集合转换到map 方便过去具体的策略类
*/
@PostConstruct
public void init() {
System.err.println(strategy);
strategyMap = strategy.stream().collect(Collectors.toMap(WithdrawStrategy::getType, a -> a));
}
/**
* 根据类型获取策略类
*/
public static WithdrawStrategy getInstance(Integer type) {
return strategyMap.get(type);
}
}
init方法中 打印List<WithdrawStrategy> strategy 发现spring自动将WithdrawStrategy接口的所有实现类放入了集合中
[
****.****.withdraw.impl.AlipayPaymentStrategy,
****.****.withdraw.impl.PaymentOnBehalfStrategy,
****.****.withdraw.impl.ThirdPartyPaymentStrategy
]
还测试了 set ,效果和list相同
测试map, 这里要注意 key 一定要是String类型,打印结果 key为类名,value为策略类实例
{
alipayPaymentStrategy=xxxxx.withdraw.impl.AlipayPaymentStrategy@3b41e1bf,
paymentOnBehalfStrategy=xxxxx.withdraw.impl.PaymentOnBehalfStrategy@619c93ca,
thirdPartyPaymentStrategy=xxxxx.withdraw.impl.ThirdPartyPaymentStrategy@486e9d1d
}