Kotlin-在Android中转换Singleton DatabaseController的最佳方法 [英] Kotlin - Best way to convert Singleton DatabaseController in Android
问题描述
我正在从"Kotlin in Action"中学习Kotlin,并且正在慢慢将Android应用程序代码转换为Kotlin.但是我在转换以下类时发现了一些问题.
I'm learning Kotlin from "Kotlin in Action" and I'm slowly converting an Android app code to it. But I have found some problem in converting the following class.
public class DatabaseController {
private static DatabaseController sDatabaseController;
private SQLiteDatabase mDatabase;
private DatabaseController(Context context) {
mDatabase = new SQLiteOpenHelperImpl(context.getApplicationContext())
.getWritableDatabase();
}
public static DatabaseController getDatabaseController(Context context) {
if (sDatabaseController == null) {
sDatabaseController = new DatabaseController(context);
}
return sDatabaseController;
}
public void addElement(Element element) {
if (element != null) {
ContentValues values = getContentValues(element);
mDatabase.beginTransaction();
try {
// insert element
mDatabase.setTransactionSuccessful();
} finally {
mDatabase.endTransaction();
}
}
}
我想出了两种不同的Kotlin实现,但是它们都没有完全说服我.哪一个可以被认为是更好的解决方案?还是存在更好的第三个?
I've come up with two different Kotlin implementation, but neither of them fully convince me. Which one can be considered a better solution? Or does exist a third one that is better?
使用对象的第一个实现
object DatabaseControllerObject {
private var mDatabase : SQLiteDatabase? = null
fun initDatabase(context: Context) {
mDatabase = mDatabase?: SQLiteOpenHelperImpl(context.applicationContext).writableDatabase
}
fun addElement(context: Context, element: Element) {
initDatabase(context)
// insert alarm
mDatabase?.let {
// CODE
}
}
第二个实现,所有内容都放在一个文件中,在每个需要数据库的活动的onCreate()中,我在其中调用initDatabase(..)
Second implementation with everything in a single file, where I call initDatabase(..) in the onCreate() of each activity that needs the database
private var mDatabase: SQLiteDatabase? = null
fun initDatabase(context: Context) {
mDatabase = mDatabase ?: SQLiteOpenHelperImpl(context.applicationContext).writableDatabase
}
fun addElement(element: Element) {
val values = getContentValues(element)
mDatabase?.let {
it.beginTransaction()
try {
// insert
it.setTransactionSuccessful()
} finally {
it.endTransaction()
}
}
}
推荐答案
我认为您想要的是同伴对象:
I think what you want is a companion object:
class DatabaseController
{
private constructor(context: Context)
{
// ...
}
companion object
{
private var instance: DatabaseController? = null
fun getInstance(context: Context): DatabaseController
{
if(instance == null)
{
instance = DatabaseController(context)
}
return instance!!
}
}
}
然后您可以这样称呼它:
Then you can just call it like this:
val databaseController = DatabaseController.getInstance(context)
这篇关于Kotlin-在Android中转换Singleton DatabaseController的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!