3 回答

TA貢獻1836條經驗 獲得超4個贊
假設每個版本都anOtherFunction接受兩個整數并返回一個整數,我只會讓該方法接受一個函數作為參數,使其成為高階。
接受兩個相同類型參數并返回相同類型對象的函數稱為 a BinaryOperator。您可以向方法中添加該類型的參數以傳遞函數:
// Give the method an operator argument
public void doSomething(BinaryOperator<Integer> otherMethod) {
int a = 6;
int b = 7;
// Then use it here basically like before
// "apply" is needed to call the passed function
int c = otherMethod.apply(a,b);
while(c < 50)
c++;
}
}
您如何使用它取決于您的用例。作為使用 lambda 的一個簡單示例,您現在可以這樣稱呼它:
doSomething((a, b) -> a + b);
它只是返回的總和a及b。
但是,對于您的特定情況,您可能會發現將其doSomething作為接口的一部分并不是必需的或最佳的。如果相反,anOtherMethod需要提供什么?不要期望您的類提供 a doSomething,而是讓它們提供 a BinaryOperator<Integer>。然后,當您需要從 獲取結果時doSomething,從類中獲取運算符,然后將其傳遞給doSomething。就像是:
public callDoSomething(HasOperator obj) {
// There may be a better way than having a "HasOperator" interface
// This is just an example though
BinaryOperator<Integer> f = obj.getOperator();
doSomething(f);
}

TA貢獻1900條經驗 獲得超5個贊
這看起來是模板方法模式的一個很好的例子。
放入
doSomething
一個基類。abstract protected anotherMethod
也在該基類中聲明,但不提供實現。然后每個子類為 提供正確的實現
anotherMethod
。

TA貢獻1828條經驗 獲得超3個贊
這就是您如何實現 Thilo 在以下演示中談到的技術:
主要類:
public class Main extends Method {
public static void main(String[] args) {
Method m = new Main();
m.doSomething();
}
@Override
public int anOtherMethod(int a, int b) {
return a + b;
}
}
抽象類:
public abstract class Method {
public abstract int anOtherMethod(int a, int b);
public void doSomething() {
int a = 6;
int b = 7;
int c = anOtherMethod(a, b);
System.out.println("Output: "+c);
}
}
這樣,您所要做的就是anOtherMethod()在要使用doSomething()方法的不同實現的每個類中進行覆蓋anOtherMethod()。
添加回答
舉報