我在类里面得到了近 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/