【问题标题】:Is it a good practice to have an interface which has default implementation for all of its methods? [closed]拥有一个所有方法都具有默认实现的接口是一种好习惯吗? [关闭]
【发布时间】:2020-08-19 07:27:43
【问题描述】:

想象一下我有一个如下界面:

public interface DataChecker<T, C> {

    default ProcessResult beforeProcess(T record, CountertHelper countertHelper, C config){
        return new ProcessResult(false, Collections.emptyList());
    }

    default List<String> checkData(T record, CountertHelper countertHelper, C config) {
        return Collections.emptyList();
    }

    @RequiredArgsConstructor
    @Getter
    class ProcessResult {
        private final boolean skip;
        private final List<String> keys;

        public ProcessResult(boolean skip) {
            this.skip = skip;
            this.keys = Collections.emptyList();
        }
    }
} 

此接口的一些实现者可能只实现beforProcess 方法,而另一些可能只实现checkData 方法,而其他一些实现者可能选择同时实现这两种方法。

将它们都设为default 是一个好习惯吗?或者更一般地说,拥有一个对所有方法都有default 实现的接口是一个好习惯。

【问题讨论】:

  • 为什么不将你的接口拆分为 2 个不同的接口,每个接口都有一个方法,根据使用情况,该类可以实现任何一个或两个。
  • 在我看来(因为它是我的意见,我投票关闭它)只是因为你可以在新接口中添加默认方法,并不意味着你应该。这意味着他们可以将方法添加到旧接口而不会导致应用程序到处崩溃,因为向后兼容,而不是你可以将它放在新接口中
  • 我认为这违背了界面目的。当您要确保对象上存在几个函数(接口)并且添加行为和功能在类范围内时,通常会使用接口。正如@Stultuske 提到的,添加了默认方法是为了向后兼容。默认实现可以在实现接口的单独默认开放类中定义。
  • 您总是可以定义一个接口,然后定义一个默认实现(在 AWT/Swing 中,一个“适配器”)。或者直接定义超类而不定义接口(这更接近你想要做的)。默认方法是一种在不破坏兼容性的情况下解决修改现有接口问题的方法,它们并不意味着改变接口的使用。

标签: java java-8 interface


【解决方案1】:

顾名思义,java 8 中的 default 方法是简单的默认。如果你不覆盖它们,它们就是调用者类将调用的方法。

如果 Some 类只想要 beforProcess 而不想要 checkData ,反之亦然,我建议您将您的界面拆分为 2

喜欢

public interface DataChecker<T, C> {

     List<String> checkData(T record, CountertHelper countertHelper, C config);

public interface DataProcessor<T, C> {

     ProcessResult beforeProcess(T record, CountertHelper countertHelper, C config);

现在方法更简洁了,如果同时实现了两个类,则类会覆盖一个或两者,因此是一种更简洁的方法。

【讨论】:

    猜你喜欢
    • 2014-07-01
    • 2020-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-22
    • 2012-03-01
    • 1970-01-01
    • 2021-03-25
    相关资源
    最近更新 更多