[英]Refactoring - Methods share the same code except for one function call
I have several methods in class Test which have the same code except one specific method call. 我在类Test中有几个方法,除了一个特定的方法调用之外,它们具有相同的代码。 Is there a possibility to merge these methods together (bellow into function foo) and call foo and tell it which method to call without doing a bigger switch or if/else statement?
是否有可能将这些方法合并在一起(下面显示为函数foo)并调用foo并告诉它在不执行更大的开关或if / else语句的情况下调用哪个方法? An important note is that foo is only called from inside the class Test (therefore foo is private) and the function foo itself calls different methods from one class Bar.
一个重要的注意事项是foo仅从类Test中调用(因此foo是私有的),函数foo本身从一个类Bar调用不同的方法。 Class Bar and Test are not in the same inheritance tree.
类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*/
}
/* ... */
}
Sure straight forward I'd add some kind of switch("which Method to call") statement. 当然直接我会添加某种开关(“哪个方法来调用”)语句。 But is there a better way to do this?
但是有更好的方法吗?
You can pass the method to call as an argument. 您可以将该方法作为参数传递。 Let's assume that the method to call has the following signature:
我们假设要调用的方法具有以下签名:
private void m() {...}
You could write: 你可以写:
private void foo(Runnable methodToRun) {
//...
methodToRun.run();
//...
}
and your various foo methods would be like: 你的各种foo方法就像:
private void foo1() { foo(new Runnable() { public void run() { someMethod(); } }); }
With Java 8 you could also pass a lambda or a method reference. 使用Java 8,您还可以传递lambda或方法引用。
As assylias said, you can use Method References with Java 8. 正如assylias所说,您可以在Java 8中使用方法引用 。
public void testAdds() {
doTest(this::addOne);
doTest(this::addTwo);
}
private void doTest(Function<Integer,Integer> func) {
System.out.println("Func(41) returns " + func.apply(41));
}
public int addOne(int num) {
return num + 1;
}
public int addTwo(int num) {
return num + 2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.