我有一個如下所示的界面。我可以限制實作此介面的所有類為它沒有實作的 QueryEngine 呼叫 getValue 嗎?目標是避免此邏輯溢位到已實作的類(因為有許多實作此介面的抽象類)。
public interface Node {
<T> T getValue(QueryEngine engine, Class<T> context);
}
現在在實作的類中,相同的函式看起來像這樣
public <T> T getValue(QueryEngine engine, Class<T> context) {
if (engine == QueryEngine.VALUE1) {
return getValue1CustomFunction(engine, context);
}
return getValue1CustomFunction(engine, context); //There are no other implementations right now
}
public <T> T getValue1CustomFunction(QueryEngine engine, Class<T> Context) {
final String expression = String.format(Value1_PATTERN, arguments.get(0).getValue(engine, String.class));
return queryBuilder(context, expression);
}
或者,對于具有某些特定于平臺的可插入覆寫的通用實作的任何建議也是受歡迎的(因為只有一個實作)
uj5u.com熱心網友回復:
你想要的東西是不可能的。
相反,您可以AbstactNode使用此通用邏輯創建一些根抽象類。并將方法標記getValue為final。似乎您想創建兩個函式(可能是抽象函式),如getValueByQueryEngine和getValueWithoutQueryEngine。
喜歡:
public abstract class Node {
public final <T> T getValue(QueryEngine engine, Class<T> context) {
if (engine == QueryEngine.VALUE1) {
return getValueByQueryEngine(engine, context);
}
return getValueWithoutQueryEngine(engine, context);
}
protected abstract <T> T getValueByQueryEngine(QueryEngine engine, Class<T> context);
protected abstract <T> T getValueWithoutQueryEngine(QueryEngine engine, Class<T> context);
}
可能有用: 為什么 Java 8 介面方法中不允許使用“final”?
同樣在這個抽象類中,您可能希望使用以下集合之一:
Set<QueryEngine> queryEngineSupportingGetValue;Map<QueryEngine, BiFunction> getValueOfQueryEngineFunctions;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/311203.html
