java - 这种情况的最佳解决方案(设计模式)是什么?

标签 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");
    }
}

你能告诉我一些合适的设计模式吗?

最佳答案

这正是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/

相关文章:

java - 谁真正实现了可序列化的方法?

java - 不要关闭外部点击时的弹出窗口

java - 通过 Java 中的元素串联合并字符串列表

java - 在 Controller 和服务之间共享相同的方法前置条件逻辑?

javascript - 使用 JavaScript/jQuery 的双重或多重回调设计模式

java - 从 github 克隆现有 Android 项目时出错

java - 未打开顶部的 Activity

java - 在 java 中链接异步调用的最优雅的解决方案?

ruby - 编写 'If it doesn' t 工作的正确方法,修复它并在 Ruby 中重试'函数

javascript - 为什么, Hook 到对象的函数中的默认上下文不是它本身