代码拉取完成,页面将自动刷新
package com.gitee.designpattern.strategy;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;
/**
* 用户支付策略工厂
*
* @author codeboy zhou
*/
public class UserPaymentStrategyFactory {
/**
* 存储用户会员等级和用户支付策略的对应关系
*/
private static Map<UserVipLevelEnum, UserPaymentStrategy> strategies;
// 自动注册所有的支付策略
static {
autoRegisterAllPaymentStrategies();
}
/**
* 自动注册所有的支付策略
*/
private static void autoRegisterAllPaymentStrategies() {
strategies = new HashMap<>(UserVipLevelEnum.values().length);
// 此处用到了 java.util.ServiceLoader 类来获取 UserPaymentStrategy 接口的所有实现类
// 该类的具体使用方式可以参考网络上其它相关的资源,这里不再赘述
ServiceLoader.load(UserPaymentStrategy.class).forEach(paymentStrategy -> {
// 获取用户会员等级注解
UserVipLevel userVipLevel = paymentStrategy.getClass().getAnnotation(UserVipLevel.class);
strategies.put(userVipLevel.value(), paymentStrategy);
});
}
/**
* 根据用户会员等级选择合适的用户支付策略
*
* @param userVipLevel 用户会员等级
*
* @return 对应的用户支付策略
*/
public static UserPaymentStrategy getUserPaymentStrategy(UserVipLevelEnum userVipLevel) {
return strategies.get(userVipLevel);
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。