【发布时间】:2016-07-24 14:37:28
【问题描述】:
我目前正在开发一个与 SQLite 数据库进行大量通信的 Android 项目。我也在尝试在应用程序中实现 MVP 框架。
我当前对 Singleton 实例的实现类似于以下内容。 (取自这篇文章:https://github.com/codepath/android_guides/wiki/Local-Databases-with-SQLiteOpenHelper)
public class PostsDatabaseHelper extends SQLiteOpenHelper {
private static PostsDatabaseHelper sInstance;
public static synchronized PostsDatabaseHelper getInstance(Context context) {
if (sInstance == null) {
sInstance = new PostsDatabaseHelper(context.getApplicationContext());
}
return sInstance;
}
private PostsDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
使用上面的现有代码,我在几个 Presenter 类中调用 getInstance 方法,将 Activity/Fragment 传递的 Context 对象传递给每个类。 Context 对象可以跨多个类传递。
我想在应用程序启动时只实例化一次 databaseHelper,而不是上面的代码,然后所有引用都将指向 getInstance 方法的变体,而没有上下文依赖。
编辑:我的主要目的是尽可能多地删除 Presenter 类中存在的 Context 对象,从而使代码“更干净”。因为所有对 getInstance 的调用都提供/注入相同类型的 Context(应用程序的上下文而不是特定于 Activity 的上下文),所以我认为不需要将 Context 对象作为参数。
public class PostsDatabaseHelper extends SQLiteOpenHelper {
private static PostsDatabaseHelper sInstance;
// called by all other classes
public static synchronized PostsDatabaseHelper getInstance() {
if (sInstance == null) {
//throw error
}
return sInstance;
}
// only called once at the start of the Application
public static void instantiateInstance(Context context){
sInstance = new PostsDatabaseHelper(context.getApplicationContext());
}
private PostsDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
我想知道的是,这种方法会有什么缺点吗?谢谢!
【问题讨论】:
标签: android singleton mvp sqliteopenhelper