要進一步擴展Ray Toal's original answer,值得注意的是,使用匿名內部類將有助於避免爲每個操作創建單獨的類文件。所以具有10個左右函數的原始類可以保持相同的方式,除了被重構爲使用Executor
模式。
此外,當使用Executor
模式時,您必須注意在原始代碼中使用this
。假設原來的功能如下:
public boolean operation1() {
SQLiteDatabase database = this.getWritableDatabase();
try {
//Code for Operation 1
return true;
} catch (SQLiteException e) {
Log.e(this.getClass().getName(), e.getMessage());
return false;
} finally {
database.close();
}
}
public boolean operation2() {
SQLiteDatabase database = this.getWritableDatabase();
try {
//Code for Operation 2
return true;
} catch (SQLiteException e) {
Log.e(this.getClass().getName(), e.getMessage());
return false;
} finally {
database.close();
}
}
隨着定義爲Executor
類如下:
public class Executor {
public static boolean runOperation(SQLiteOpenHelper helper, Operation operation) {
SQLiteDatabase database = helper.getWritableDatabase();
try {
operation.run(database);
return true;
} catch (SQLiteException e) {
Log.e(helper.getClass().getName(), e.getMessage());
return false;
} finally {
database.close();
}
}
}
並將其定義爲Operation
界面如下:
public interface Operation {
public void run(SQLiteDatabase database) throws SQLiteException;
}
原來的功能現在重寫如下:
public boolean operation1() {
return Executor.runOperation(this, new Operation() {
public void run(SQLiteDatabase database) throws SQLiteException {
//Code for Operation 1
}
});
}
public boolean operation2() {
return Executor.runOperation(this, new Operation() {
public void run(SQLiteDatabase database) throws SQLiteException {
//Code for Operation 2
}
});
}
此擴展還糾正了Ray在其原始答案中忽略的錯誤。
你寫了一個輔助方法。 – Maroun
如果'try'中的代碼不同,那麼您將無法有效地重構它。更好的模式是將所有的數據庫交互放到一個單獨的類/方法集中,所以你幾乎不需要看它。 –
@ChrisHayes:它可以使用接口(使用單一方法)重構,然後傳遞給輔助方法。 –