use*_*979 2 java design-patterns
我有一些非常相似的功能,但每个功能中有一行不同.
如何避免代码重复?
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");
}
}
Run Code Online (Sandbox Code Playgroud)
你能告诉我一些合适的设计模式吗?
这正是Lambda表达式的用途:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
123 次 |
| 最近记录: |