我有一些非常相似的函数,但每个函数中有一行不同。
如何避免代码重复?
public class Example{
public void f(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct1(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
public void g(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct2(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
public void h(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct3(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
public void i(){
System.out.println("Start");
OtherExample.start();
AnotherExample.funct4(); //DIFFERENT CODE LINE
OtherExample.end();
System.out.println("End");
}
}
你能告诉我一些合适的设计模式吗?
最佳答案
这正是Lambda Expressions用于:
public static void f(Runnable r) {
System.out.println("Start");
OtherExample.start();
r.run();
OtherExample.end();
System.out.println("End");
}
public static void main(String[] args) {
f(AnotherExample::funct1);
f(AnotherExample::funct2);
f(AnotherExample::funct3);
f(AnotherExample::funct4);
}
关于java - 这种情况的最佳解决方案(设计模式)是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25939699/