public class Person {
private Long id;
private String name;
private Integer minAge;
private Integer maxAge;
private Person() {
}
public static class Builder {
private Person person = new Person();
public Builder id(Long id) {
person.id = id;
return this;
}
public Builder name(String name) {
person.name = name;
return this;
}
public Builder minAge(Integer minAge) {
person.minAge = minAge;
return this;
}
public Builder maxAge(Integer maxAge) {
person.maxAge = maxAge;
return this;
}
public Person build() {
if (person.minAge != null && person.maxAge != null) {
if (person.minAge < 0) {
throw new IllegalArgumentException("minAge必须大于等于0");
}
if (person.maxAge <= person.minAge) {
throw new IllegalArgumentException("maxAge必须大于等于minAge");
}
} else if ((person.minAge == null && person.maxAge != null) ||
(person.minAge != null && person.maxAge == null)) {
throw new IllegalArgumentException("minAge和maxAge必须同时设置");
}
return person;
}
}
}
评论