![](/img/trans.png)
[英]I need clarity on specific condition on default method in interface in java
[英]Validate a condition in default method in interface in Java
我的接口中有一個由許多類實現的方法:
public interface MyInterface {
Message createMessage(List<String> rawStrings);
}
我在所有createMessage
實現中添加了一個 Validate 條件:
public Message createMessage(List<String> rawStrings) {
Validate.isTrue(!rawStrings.isEmpty(), "No rawstrings present");
.....
}
有人建議我將驗證條件移動到接口 - 但這樣做,我將失去執行實現我的接口的 class 來實現此方法的機會。
這看起來是個好主意嗎?
default Message createMessage(List<String> rawStrings) {
Validate.isTrue(!rawStrings.isEmpty(), "No rawstrings present");
return null;
}
這是對接口中默認方法的良好使用嗎? 我怎樣才能確保實現 MyInterface 的MyInterface
也實現方法createMessage
?
default
關鍵字的最初目的是在不破壞現有實現的情況下向現有接口添加功能。 Java 語言團隊不情願地采用這種方法作為解決方案(即,不是強制所有List
實現都實現新方法,而是將default
方法添加到List
)。 通常,將通用代碼移入default
方法是不可取的。
引入抽象基 class (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);
}
然后,每個實現 class 都擴展了 ABC:
public class MyClass extends MyAbstractBaseClass {
@Override
protected Message createValidMessage(List<String> rawStrings) {
// ...do something...
}
}
這是模板方法模式的實現,它要求實現類僅提供驗證后邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.