function.apply-method在自定义接口中不被覆盖时做什么?

vcirk6k6  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(539)

在下面的示例代码中,我很难理解“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;
    } 
}
wqnecbli

wqnecbli1#

apply方法到底在做什么,因为它没有被覆盖?
取决于所选接口的静态方法。万一 isEmailValid 的身体 apply 方法是

customer.getEmail().contains("@") ? ValidationResult.SUCCESS : ValidationResult.EMAIL_NOT_VALID;

它显然返回了结果validationresult,但是没有代码支持它。
就在那里,一个 CustomerRegistrationValidator 示例由lambda定义。
想象一下你不得不重写这个

static CustomerRegistrationValidator isEmailValid() {
  return new CustomerRegistrationValidator() {
    @Override
    public ValidationResult apply(Customer customer) {
      return customer.getEmail().contains("@") ? ValidationResult.SUCCESS : ValidationResult.EMAIL_NOT_VALID;
    }
  };
}

到lambda语法。你会得到你现在所拥有的。

相关问题