前言
记录下工作中用到的一些模板和设计模式
提示:以下是本篇文章正文内容,下面案例可供参考
一、执行器
代码中if过多代码显得冗余,参考了一下网上的文档自己写了个执行器
二、代码
1.条件传输类
代码如下(示例):
@Data
@Builder
public class RuleDto{
private String name;
private Integer age;
}
2.规则接口
代码如下(示例):
public interface BaseRule{
Boolean execute(RuleDto dto);
}
3.规则抽象类
代码如下(示例):
public abstract class AbstractRule implements BaseRule{
protected <T> T convert(RuleDto dto){
return <T> dto;
}
protected <T> boolean executeRule(T t){
return true;
}
@Override
public Boolean execute(RuleDto dto) {
return executeRule(convert(dto));
}
}
4.规则处理器
代码如下(示例):
public class RuleService{
private Map<Integer , List<BaseRule>> hashMap = new HashMap<>();
private static final int AND = 1;
private static final int OR = 0;
public static RuleService instance(){
return new RuleService
}
public RuleService and(List<BaseRule> ruleList){
hashMap.put(AND,ruleList);
return this;
}
public RuleService or(List<BaseRule> ruleList) {
hashMap.put(OR, ruleList);
return this;
}
private boolean and(RuleDto dto, List<BaseRule> ruleList) {
for (BaseRule rule : ruleList) {
Boolean excute = rule.execute(dto);
if (!excute) {
return false;
}
}
return true;
}
private boolean or(RuleDto dto, List<BaseRule> ruleList) {
for (BaseRule rule : ruleList) {
Boolean excute = rule.execute(dto);
if (excute) {
return true;
}
}
return false;
}
public boolean execute(RuleDto dto) {
for (Map.Entry<Integer, List<BaseRule>> item : hashMap.entrySet()) {
List<BaseRule> ruleList = item.getValue();
switch (item.getKey()) {
case AND:
System.out.println("execute key=" + 1);
if (!and(dto, ruleList)) {
return false;
}
break;
case OR:
System.out.println("execute key =" + 0);
if (!or(dto, ruleList)) {
return false;
}
break;
default:
break;
}
}
return true;
}
}
5.规则实例
代码如下(示例):
@Builder
public class NameRule extends AbstractRule {
@Override
public Boolean execute(RuleDto dto) {
if(dto.getName.equals("张三")){
System.out.println("这是张三");
}else {
System.out.println("这不是张三");
}
return dto.getAddress().startsWith(MATCH_ADDRESS_START);
}
}
@Builder
public class AgeRule extends AbstractRule {
@Override
public Boolean execute(RuleDto dto) {
if(dto.getAge()>=18){
System.out.println("成年了");
return true;
}else {
System.out.println("未成年");
return false;
}
}
6.测试
代码如下(示例):
public class RuleServiceTest {
public static void main(String[] args) {
RuleDto ruleDto = RuleDto.builder().name("张三").age(18).build();
AgeRule2 build = AgeRule2.builder().build();
NameRule2 build1 = NameRule2.builder().build();
boolean execute = RuleService.instance().and(Arrays.asList(build1, build)).execute(ruleDto);
System.out.println(execute);
}
}
控制台and如下(示例):
总结
提示:开发任务赶还是用if吧,这个也算不上优化了啥就美化下业务代码,看这代码的感觉有点像工作流的部分代码,应该用到了类似的逻辑
|