1

我真的很喜欢活动记录的想法,我将实现以下设计:所有具体模型都扩展抽象模型,它具有基本的 CRUD 操作。

这是模型上的示例保存功能:

public void save(){
    try {
        getDao().createOrUpdate(this);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

这是getDao():

private static Dao<Model, Integer> getDao(Context context){
    Dao<Model, Integer> result = null;

    DatabaseHelper dbHelper = new DatabaseHelper(context);
    try {
        result = dbHelper.getDao(Model.class);
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       

    return result;
}

如您所见,我有 Model.class。除了将 Class 传递给 getDao 函数之外,还有其他选项或模式可以实现以下设计吗?

4

1 回答 1

3

不要将getDao方法设为静态,然后:

result = dbHelper.getDao(getClass());

编辑:

在这种情况下,您将不得不以某种方式告诉 getDao 方法要获取什么 dao。你可以使用类似的东西:

private static <T> Dao getDao(Context context, T object){
    try {
        return new DatabaseHelper(context).getDao(object.getClass());
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}
于 2012-04-16T17:17:43.070 回答