Ai
1 Star 1 Fork 0

codeboyzhou/design-pattern

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
UserPaymentStrategyFactory.java 1.50 KB
一键复制 编辑 原始数据 按行查看 历史
codeboyzhou 提交于 2020-05-08 11:16 +08:00 . 策略模式及其优化
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);
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/codeboyzz/design-pattern.git
git@gitee.com:codeboyzz/design-pattern.git
codeboyzz
design-pattern
design-pattern
master

搜索帮助