如何在 Java 中链接函数调用?

Max*_*fal 5 java functional-programming java-8

我有两段类似的代码:

void task1() {
    init();
    while(someCondition) {
      doSomething();
    }
    shutdown();
  }
Run Code Online (Sandbox Code Playgroud)
void task2() {
    while(someCondition) {
      init();
      doSomething();
      shutdown();
    }
  }
Run Code Online (Sandbox Code Playgroud)

我想避免代码重复,我认为这可以通过使用函数式方法来完成。我想将循环和 init/shutdown 调用放在单独的函数中,然后链接它们的调用(不是 Java 8 Function 接口,更多的伪代码):

Function setup(Function f){
    init();
    f();
    shutdown();
}
Run Code Online (Sandbox Code Playgroud)
Function loop(Function f){
    while(someCondition) {
      f();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我想像这样链接这些:

void task1() {
   setup(loop(doSomething));
 }
Run Code Online (Sandbox Code Playgroud)
void task2() {
    loop(setup(doSomething));
  }
Run Code Online (Sandbox Code Playgroud)

我想到了 Java 的 Function 接口中的 compose/andThen 但它们不合适,因为它们只将一个函数的返回值传递给下一个函数。有没有人知道如何使用 Java 8 或不同的方法来做到这一点?

Swe*_*per 10

你确实可以做到这一点。您需要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();
}
Run Code Online (Sandbox Code Playgroud)

还应该注意的是,虽然在函数式程序员看来,第一个代码可能看起来“重复”,但对于 Java 程序员来说,第一个代码非常好。以这种方式重写它可能会让不习惯函数式风格的人更加困惑。