最佳答案
在 Java8中使用 默认的方法作为穷人版本的特征是一种安全的做法吗?
Some claim it may make pandas sad if you use them just for the sake of it, because it's cool, but that's not my intention. It is also often reminded that default methods were introduced to support API evolution and backward compatibility, which is true, but this does not make it wrong or twisted to use them as traits per se.
我想到了 下面的实际用例:
public interface Loggable {
default Logger logger() {
return LoggerFactory.getLogger(this.getClass());
}
}
或者,定义一个 PeriodTrait
:
public interface PeriodeTrait {
Date getStartDate();
Date getEndDate();
default isValid(Date atDate) {
...
}
}
诚然,可以使用组合(甚至是 helper 类) ,但它似乎更加冗长和混乱,不允许从多态性中获益。
那么,是 使用默认方法作为基本特征是否可行/安全还是我应该担心不可预见的副作用呢?