利用Builder模式实现数据校验

写作背景

N/A

需求说明

假设有一个用户类Person,含有若干个字段,需要对这些字段进行数据合法性校验,当遇到非法数据的时候需要手机号错误信息反馈给调用方

实现思路

借助Builder模式设计一个校验器,通过校验器验证各数据字段的合法性,并收集错误信息
这样做的好处在于,校验器相对独立,具有良好的扩展性

具体实现

实体类的构造中引入了lombok:1.16.16,以通过注解的方式消除模板代码

Person类
@Data
@AllArgsConstructor
public class Person {
    private String name;
    private String address;
}
PersonValidator类
public class PersonValidator {

    private Person person;
    private List errMsg;

    public static List validate(Person person) {
        return new PersonValidator()
            .init(person)
            .nameShouldNotEmpty()
            .lengthOfAddressShouldNotLessThan10()
            .collectErrMsg();
    }

    private PersonValidator init(Person person) {
        this.person = person;
        this.errMsg = new ArrayList<>();
        return this;
    }

    private PersonValidator nameShouldNotEmpty() {
        if (isEmpty(this.person.getName())) {
            errMsg.add("name should not empty.");
        }
        return this;
    }

    private PersonValidator lengthOfAddressShouldNotLessThan10() {
        if (StringUtils.length(this.person.getAddress()) <= 10) {
            errMsg.add("length of address should not less than 10");
        }
        return this;
    }

    private List collectErrMsg() {
        return this.errMsg;
    }
    
}
测试

1) 当address属性为BeiJing时,长度小于10,应报错

@Test
public void validate() throws Exception {
    Person person = new Person("Tom", "BeiJing");
    List errMsg = PersonValidator.validate(person);
    System.out.println(errMsg);  //length of address should not less than 10
}

2) 属性均满足校验条件时,不输出错误信息

@Test
public void validate() throws Exception {
    Person person = new Person("Tom", "BeiJing ChaoYang");
    List errMsg = PersonValidator.validate(person);
    System.out.println(errMsg);  // print nothing
}

你可能感兴趣的:(利用Builder模式实现数据校验)