java - 如何在方法之间正确传递上下文以使用数据库存储库?

标签 java android sqlite architecture software-design

好吧,这是一个更理论化的问题。

我有PlayerRepository。这是一个用于在我的 SQLite 数据库上执行操作的类。我已经实现了诸如 selectinsertupdate 等操作。

public PlayerRepository(Context context) {
    super(context, com.fixus.portals.model.Player.class);
    open();
}
构造函数中的

super 是因为 PlayerRepository extends Repository 这也是我的类。 Repository 最重要的部分就是这个

public class Repository<T> {
protected static SQLiteDatabase db = null;
protected static MainHelper helper = null;
protected Context context;
private Class<T> type;

public Repository(Context context, Class<T> classz) {
    this.type = classz;
    this.context = context;
    if(helper == null) {
        helper = new MainHelper(context.getApplicationContext());
    } 
}

public static void open() {
    if(db == null) {
        db = helper.getWritableDatabase();
    }
}
}

正如您所看到的,当我创建存储库时,如果之前未打开数据库,我将打开数据库。为此,我需要传递应用程序/Activity 的Context。这不是问题

但有时我想在 Activity 之外使用我的存储库。在某种需要获取数据的工具类中。所以我可以考虑两种方法

  1. 我在 Activity 中获取数据并将其传递给我的工具类/方法,因此我不需要在其中使用存储库。这不太灵活

  2. 我需要将上下文传递给我的工具类/方法。但这意味着每种操作都需要接收上下文,我不确定这是一个好方法

我错过了什么吗?有没有更好的处理方法?

最佳答案

您总是需要一个上下文来访问 SQLite 数据库,因此您可以做的是更改该特定工具类的构造函数并传递一个新的 PlayerRepository 实例作为参数。这可以防止您的工具类本身需要上下文。

我认为,如果您有多个使用数据库的类,最好的方法是创建一个新类,其唯一的工作是执行数据库操作,并将所有需要的操作放入该类中。

只需使用当前 Activity 的上下文到 ToolsPlayerRepository 构造函数创建此数据库类的对象。这样,您的 PlayerRepositoryTools 类都不需要 Context,并且都可以对数据库执行操作。 即使您确实需要 PlayerRepository 中的 Context,最好还是将所有与数据库相关的函数集中在一个类中。

关于java - 如何在方法之间正确传递上下文以使用数据库存储库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32026224/

相关文章:

mysql - 将数据从一个表复制到另一个表时出现错误,sqlite

python - 将列表列表的输出格式化为列

java - native JNI 文件无法在 Android Studio 中找到 Java 文件的路径

android - Kotlin 协程 - 优雅地处理来自挂起函数的错误

java - 无法让程序使用用户输入

java - 如何根据随机结果更改骰子滚轮的ImageView

Android在哪里存储可编辑文件

android - 如果 SQL 查询没有返回数据,游标的值是多少?

java - Eclipse 不断执行清理/构建的问题

java - 将字符串中的特殊字符替换为其他特殊字符