java - 从函数中删除公共(public)代码

标签 java

我在类里面得到了近 10 个具有类似模式的函数,例如以下函数

    SQLiteDatabase database = this.getWritableDatabase();

    try {
          //Some different code , all other code(try,catch,finally) is same in all functions
    } catch (SQLiteException e) {
        Log.e(this.getClass().getName(), e.getMessage());
        return false;
    } finally {
        database.close();
    }

}

我想从所有函数中删除通用代码(try、catch、finally)并将其移动到一个地方 我怎样才能做到这一点?

最佳答案

有许多框架可以大大简化您可以使用的数据库交互,但是如果您想自己做事,并且对 Java 方式做这样的事情感兴趣,我的想法是:

让你的“执行者”像这样:

public class Executor {
  public static void runOperation(Operation operation) {
    SQLiteDatabase database = this.getWritableDatabase();
    try {
      operation.run(database);
    } catch (SQLiteException e) {
      Log.e(operation.getClass().getName(), e.getMessage());
      return false;
    } finally {
      database.close();
  }
}

现在你想做的 10 件事中的每一件事都是操作:

public interface Operation {
  void run(SQLiteDatabase database) throws SQLiteException;
}

这是特定操作的样子:

Operation increaseSalary = new Operation() {
  public void run(SQLiteDatabase database) throws SQLiteException {
    // .... write the new increased salary to the database
  }
};

然后你运行它:

.
.
Executor.runOperation(increaseSalary);
.
.

您也可以将接口(interface)的实现设为匿名内部类,但这可能会降低可读性。

.
.
Executor.runOperation(new Operation() {
  public void run(SQLiteDatabase database) throws SQLiteException {
    // put the increase salary database-code in here
  }
});
.
.

您可以查看经典设计模式列表以找出这是哪一个。

关于java - 从函数中删除公共(public)代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20931619/

相关文章:

java - 文件提供者 : Failed to find configured root

java - MapReduce任务立即从0%跳到100%,没有输出

java - 在 JPanel 中刷新整数

java - Eclipse PropertySheetPage - 它可以支持多行属性吗?

java - 我怎样才能在显示器上显示不同的图像:column based on other column's value?

java - 如何在 Netbeans 中为未修饰的 JFrame 添加阴影

java - Spring Cloud Stream - 应用程序初始化后发送消息

Java网络服务: null request parameter

java - 配置 eclipse 以将 .esp 作为 jsp 文件查看

java - java中如何上传文件