首页 > 解决方案 > 在Java接口中验证默认方法中的条件

问题描述

我的界面中有一个由许多类实现的方法:

public interface MyInterface {
    Message createMessage(List<String> rawStrings);
}

我在所有createMessage实现中添加了一个验证条件:

public Message createMessage(List<String> rawStrings) {
    Validate.isTrue(!rawStrings.isEmpty(), "No rawstrings present");
    .....
}

有人建议我将验证条件移动到接口 - 但这样做,我将失去强制执行我的接口的类来实现此方法。

这看起来是个好主意吗?

default Message createMessage(List<String> rawStrings) {
    Validate.isTrue(!rawStrings.isEmpty(), "No rawstrings present");
    return null;
}

这是对接口中默认方法的良好使用吗?我怎样才能确保实现的类MyInterface也实现了该方法createMessage

标签: javadesign-patternsinterfacedefault

解决方案


关键字的最初目的是在default不破坏现有实现的情况下向现有接口添加功能。Java 语言团队不情愿地采用了这种方法(即,不是强制所有 List实现都实现一个新方法,而是将一个default方法添加到List. 通常,将通用代码移入default方法是不可取的。

引入抽象基类 (ABC) 通常是一种更好的方法:

public interface MyInterface {
    Message createMessage(List<String> rawStrings);
}

public abstract class MyAbstractBaseClass implements MyInterface {

    @Override
    public Message createMessage(List<String> rawStrings) {
        Validate.isTrue(!rawStrings.isEmpty(), "No rawstrings present");
        createValidMessage(rawStrings);
    }

    protected abstract Message createValidMessage(List<String> rawStrings);
}

然后,每个实现类都扩展了 ABC:

public class MyClass extends MyAbstractBaseClass {

    @Override
    protected Message createValidMessage(List<String> rawStrings) {
        // ...do something...
    }
}

这是模板方法模式的实现,它要求实现类仅提供验证后逻辑。


推荐阅读