使用varargs的Java方法,它执行操作并打印已知结果

ytt*_*rrr 2 java variadic-functions java-8

在Java中是否可以创建类似于此execute方法的方法:

public void execute(Runnable... mrs) {
    for (Runnable mr : mrs) {
        mr.run();
        // should print some expected string here
    }
}

public void sleep(int seconds) {
    try {
        Thread.sleep(1000 * seconds);
    } catch (InterruptedException ex) {
        log.error("Error occured", ex);
    }
}

public void customExecute() {
    execute(() -> sleep(1), () -> sleep(2));
}
Run Code Online (Sandbox Code Playgroud)

但在执行每个操作后,它应该打印传递的String参数和(问题的关键时刻)它应该支持一行使用 - 类似于:

execute(("Action 1 passed") -> someAction(), ("Other action passed") -> otherAction());
Run Code Online (Sandbox Code Playgroud)

Hol*_*ger 5

您可以使用Builder Pattern的变体来完成它:

public interface Step {
    void doIt(String msg, Runnable r);
    default Step then(String msg, Runnable r) {
        doIt(msg, r);
        return this;
    }
}
public static Step execute(String msg, Runnable r) {
    Step s=(m,x)-> {
        x.run();
        System.out.println(msg);
    };
    return s.then(msg, r);
}
Run Code Online (Sandbox Code Playgroud)

然后就可以使用它了

execute("Action 1 passed", () -> someAction())
  .then("Other action passed", () -> otherAction());
Run Code Online (Sandbox Code Playgroud)

并根据需要扩展它

execute("Action 1 passed", () -> someAction())
  .then("Other action passed", () -> otherAction())
  .then("NextAction passed", () -> nextAction())
  .then("and nextAction passed again", () -> nextAction()) ;
Run Code Online (Sandbox Code Playgroud)

它也很容易适应其他执行策略,例如

static ExecutorService es=Executors.newSingleThreadExecutor();
public static Step executeInBackground(String msg, Runnable r) {
    Step s=(m,x)-> es.execute(()-> execute(m, x));
    return s.then(msg, r);
}
Run Code Online (Sandbox Code Playgroud)

可以在调用者处进行微小的更改:

executeInBackground("Action 1 passed", () -> someAction())
  .then("Other action passed", () -> otherAction())
  .then("NextAction passed", () -> nextAction())
  .then("and nextAction passed again", () -> nextAction());
Run Code Online (Sandbox Code Playgroud)

  • 使用构建器模式,它比我的示例更清晰. (2认同)