策略模式太过麻烦,所以记下策略方法。
一、策略方法
//Service Map容器
private final ConcurrentHashMap<BQSQueryDataRequestEnum, Function<Person, Result>> requestMap = new ConcurrentHashMap<>();
@PostConstruct
public void init() {
//增加三个元素
requestMap.put(BQSQueryDataRequestEnum.AA, person -> this.aa(person));
requestMap.put(BQSQueryDataRequestEnum.BB, person -> this.bb(person));
requestMap.put(BQSQueryDataRequestEnum.CC, person -> this.cc(person));
}
//控制层只调用这个方法,根据不同的枚举type,选择调用aa,bb,cc方法。
@Override
public Result queryData(Person person, String type) {
return requestMap.get(BQSQueryDataRequestEnum.getEnumByValue(type)).apply(person);
}
private Result aa(Person person) {
return new Result();
}
private Result bb(Person person) {
return new Result();
}
private Result cc(Person person) {
return new Result();
}
public enum BQSQueryDataRequestEnum {
aa("XY_BQS_TSSB", "a方法"),
bb("XY_BQS_DCTJ", "b方法"),
cc("XY_BQS_FZWL", "c方法");
BQSQueryDataRequestEnum() {
}
@Getter
private String value;
@Getter
private String desc;
BQSQueryDataRequestEnum(String value, String desc) {
this.value = value;
this.desc = desc;
}
/**
* 根据value获取enum
*
* @param value
* @return
*/
public static BQSQueryDataRequestEnum getEnumByValue(String value) {
if (Objects.isNull(value)) {
throw new MetaException(MetaErrorEnum.MissingRequiredParameter, "接口请求方式为空!");
}
Stream<BQSQueryDataRequestEnum> enumStream = Stream.of(BQSQueryDataRequestEnum.values());
if (!enumStream.anyMatch(s -> Objects.equals(s.getValue(), value))) {
throw new MetaException(MetaErrorEnum.MissingRequiredParameter, "接口请求方式参数错误!");
}
return Stream.of(BQSQueryDataRequestEnum.values()).filter(s -> Objects.equals(value, s.getValue())).findFirst().get();
}
}