java - 在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
?
解决方案
关键字的最初目的是在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...
}
}
这是模板方法模式的实现,它要求实现类仅提供验证后逻辑。
推荐阅读
- javascript - 如果我在特定的 body 类上引用 CSS 模块声明,它就不起作用
- excel - 如何以 UTF-8 将行保存到文件中?
- typescript - function () { this.array = [newElem, ...array] } 是纯的吗?
- c# - 有没有办法在带有 StorageFolders 的大量对象上使用 LocalObjectStorageHelper
- sparql - 如何精确 SPARQL CONSTRUCT 查询的结果?
- scala - Query Elastic search from spark returns empty Map for values
- macos - 在 MacOS 上使用 AVPlayer 连接到名为 rtcreportingd 的服务时出错
- c# - 策略设计模式与简单的接口抽象?
- python - 无法使用发布请求从下一页获取结果
- react-native - ViewPagerAndroid 未在 ScrollView 中显示(使用 Reacnative)