在下面的示例代码中,我很难理解“apply”方法的用法。apply方法到底在做什么,因为它没有被覆盖?很明显是在返回结果 ValidationResult
,但没有代码支持它。
public class Main {
public static void main(String[] args) {
Customer customer = new Customer("Alice", "alice@gmail.com", "0879546451", LocalDate.of(2000, 1, 1));
ValidationResult result = CustomerRegistrationValidator
.isEmailValid()
.and(CustomerRegistrationValidator.isPhoneNumber())
.and(CustomerRegistrationValidator.isAdult())
.apply(customer);
System.out.println(result);
}
}
public interface CustomerRegistrationValidator extends Function<Customer, ValidationResult> {
static CustomerRegistrationValidator isEmailValid() {
return customer -> customer.getEmail().contains("@") ? ValidationResult.SUCCESS : ValidationResult.EMAIL_NOT_VALID;
}
static CustomerRegistrationValidator isPhoneNumber() {
return customer -> customer.getPhoneNumber().contains("+08") ? ValidationResult.SUCCESS : ValidationResult.PHONE_NUMER_NOT_VALID;
}
static CustomerRegistrationValidator isAdult() {
return customer -> Period.between(customer.getDob(), LocalDate.now()).getYears() > 16 ? ValidationResult.SUCCESS : ValidationResult.IS_NOT_AN_ADULT;
}
default CustomerRegistrationValidator and (CustomerRegistrationValidator other) {
return customer -> {
ValidationResult result = this.apply(customer);
return result.equals(ValidationResult.SUCCESS) ? other.apply(customer) : result;
};
}
enum ValidationResult {
SUCCESS, PHONE_NUMER_NOT_VALID, EMAIL_NOT_VALID, IS_NOT_AN_ADULT;
}
}
1条答案
按热度按时间wqnecbli1#
apply方法到底在做什么,因为它没有被覆盖?
取决于所选接口的静态方法。万一
isEmailValid
的身体apply
方法是它显然返回了结果validationresult,但是没有代码支持它。
就在那里,一个
CustomerRegistrationValidator
示例由lambda定义。想象一下你不得不重写这个
到lambda语法。你会得到你现在所拥有的。