我有两段类似的代码:
void task1() {
init();
while(someCondition) {
doSomething();
}
shutdown();
}
void task2() {
while(someCondition) {
init();
doSomething();
shutdown();
}
}
我想避免代码重复,我认为这可以通过使用功能方法来完成。
我想将循环和 init/shutdown 调用放在单独的函数中,然后链接它们的调用(不是 Java 8 Function 接口(interface),更多伪代码):
Function setup(Function f){
init();
f();
shutdown();
}
Function loop(Function f){
while(someCondition) {
f();
}
}
然后我想像这样链接这些:
void task1() {
setup(loop(doSomething));
}
void task2() {
loop(setup(doSomething));
}
我想到了 Java 的 Function 接口(interface)中的 compose/andThen,但它们并不合适,因为它们只将一个函数的返回值交给下一个函数。有谁知道如何使用 Java 8 或其他方法来做到这一点?
最佳答案
你确实可以做到这一点。您需要Runnable
,而不是 Function
,因为您的方法不接受任何参数并且不返回任何值。但是,如果您的方法具有不同的签名,则需要使用另一种类型。
public static void init() { ... }
public static void doSomething() { ... }
public static void shutdown() { ... }
public static Runnable setup(Runnable r) {
return () -> {
init();
r.run();
shutdown();
};
}
public static Runnable loop(Runnable r) {
return () -> {
while (someCondition) {
r.run();
}
};
}
// I used "Main" here because this in a class called Main. Replace "Main" with the name of your class
public static void task1() {
setup(loop(Main::doSomething)).run();
}
public static void task2() {
loop(setup(Main::doSomething)).run();
}
还应该注意的是,虽然在函数式程序员的眼中,第一个代码可能看起来“重复”,但对于 Java 程序员来说,第一个代码是非常好的。以这种方式重写它可能会让不习惯函数式风格的人更加困惑。
关于java - 如何在 Java 中链接函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59629047/