gpt4 book ai didi

java - 重构——方法共享相同的代码,除了一个函数调用

转载 作者:行者123 更新时间:2023-11-29 05:15:43 24 4
gpt4 key购买 nike

我在类 Test 中有几个方法,除了一个特定的方法调用外,它们具有相同的代码。是否有可能将这些方法合并在一起(在下面的函数 foo 中)并调用 foo 并告诉它调用哪个方法而不用做更大的 switch 或 if/else 语句?一个重要的注意事项是 foo 仅从类 Test 内部调用(因此 foo 是私有(private)的)并且函数 foo 本身从一个类 Bar 调用不同的方法。类 Bar 和 Test 不在同一个继承树中。

class Test {

/* ... */

private void foo("Parameter that specifies which method to call from class Bar")
{
/* merged code which was equal */

Bar bar = new Bar();
bar.whichMethod(); // Call the method (from Class Bar) specified in the Parameter

/* merged code which was equal*/
}

/* ... */

}

当然,我会直接添加某种 switch("which Method to call") 语句。但是有没有更好的方法来做到这一点?

最佳答案

您可以将要调用的方法作为参数传递。假设要调用的方法具有以下签名:

private void m() {...}

你可以这样写:

private void foo(Runnable methodToRun) {
//...
methodToRun.run();
//...
}

你的各种 foo 方法就像:

private void foo1() { foo(new Runnable() { public void run() { someMethod(); } }); }

在 Java 8 中,您还可以传递 lambda 或方法引用。

关于java - 重构——方法共享相同的代码,除了一个函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26633442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com