我有一些用于不同表和查询的单例 sqlite 适配器。在那些适配器中,我发现有一些数据库启动方法和变量可以放在基类中,这样我就不需要在每个适配器中一遍又一遍地写出来。下面是我目前做的基类with the help of this thread :
基类 DatabaseHelper
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "postsDatabase";
private static final int DATABASE_VERSION = 1;
private static DatabaseHelper sInstance;
public static String MAIN_TABLE; // will be replaced when instantiated
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized DatabaseHelper getInstance(Context context) {
// Use the application context, which will ensure that you
// don't accidentally leak an Activity's context.
// See this article for more information: http://bit.ly/6LRzfx
if (sInstance == null) {
sInstance = new DatabaseHelper(context.getApplicationContext());
}
sInstance.context = context;
return sInstance;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
// Simplest implementation is to drop all old tables and recreate them
db.execSQL("DROP TABLE IF EXISTS " + MAIN_TABLE);
onCreate(db);
}
}
// will be replaced when instantiated
@Override
public void onCreate(SQLiteDatabase database) {}
@Override
public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
}
}
在适配器中使用:
public class AnimalTableAdapter{
public AnimalTableAdapter(Context context) {
dbHelper = new DatabaseHelper(context){
public static final String MAIN_TABLE = "animal";
@Override
public void onCreate(SQLiteDatabase db) {
CREATE_SEARCH_STRING_TABLE = "//****sql query**** //";
db.execSQL(CREATE_SEARCH_STRING_TABLE);
}
};
db = dbHelper.getWritableDatabase();
}
}
但是,我不认为 DatabaseHelper
基类是单例,因为 constructor
是公共(public)的,但是当我将它变成私有(private)构造函数时,我无法再覆盖动物适配器中的一些方法和变量,如 MAIN_TABLE
和 onCreate
。谁能指出制作单例基类的正确方法?
最佳答案
Can anyone point me the right way to make a singleton base class?
允许子类 B
的单例类 A
在术语上是自相矛盾的。 B
的任何实例也将是 A
。如果 B
的实例和 A
的实例同时存在,那么这将违反 A
的“单例性”。
此外,在 Java 中没有办法实现严格(静态)单例类的子类。
更好的方法是将公共(public)代码移动到原始单例类的抽象父类(super class),并将新的单例类编写为抽象类或原始单例类的子类。
我猜你可以拼凑一些东西,其中单例的构造函数是 public
并进行一些粗糙的运行时检查以查看它是否通过子类构造函数调用。但这是一个非常糟糕的主意……IMO。
关于java - Singleton Sqlite 基类的覆盖方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954072/