我的界面中有一个由许多类实现的方法:
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
?
default
关键字的最初目的是在不破坏现有实现的情况下向现有接口添加功能。 Java语言团队将此方法作为一种勉强的解决方案(即,不是强制[[all List
实现实现新方法,而是向default
添加了List
方法)。通常,不希望将通用代码移到default
方法中。
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... } }