我想创建一种更简单的方法来处理SharedPreferences。 我想称呼它的方式就像这样
获得偏好:
val email = SharedPrefs.userdata.email
val wifiOnly = SharedPrefs.connections.wifiOnly
设置偏好:
SharedPrefs.userdata.email = "someone@example.com"
SharedPrefs.connections.wifiOnly = true
我能够这样做:
App.instance
会在以下代码段中返回Context
个对象
object SharedPrefs {
val userdata by lazy { UserPreferences() }
val connections by lazy { ConnectionPreferences() }
class UserPreferences {
private val prefs: SharedPreferences = App.instance.getSharedPreferences("userdata", Context.MODE_PRIVATE)
var email: String
get() = prefs.getString("email", null)
set(value) = prefs.edit().putString("email", value).apply()
}
class ConnectionPreferences {
private val prefs: SharedPreferences = App.instance.getSharedPreferences("connections", Context.MODE_PRIVATE)
var wifyOnly: Boolean
get() = prefs.getBoolean("wifiOnly", false)
set(value) = prefs.edit().putBoolean("wifyOnly", value).apply()
}
}
问题是仍然可以调用它:SharedPrefs.UserPreferences()
我可以将此构造函数专用于此文件或对象吗?
答案 0 :(得分:3)
您可以将接口和实现类分开,并将后者private
设为对象:
object SharedPrefs {
val userdata: UserPreferences by lazy { UserPreferencesImpl() }
interface UserPreferences {
var email: String
}
private class UserPreferencesImpl : UserPreferences {
private val prefs: SharedPreferences =
App.instance.getSharedPreferences("userdata", Context.MODE_PRIVATE)
override var email: String
get() = prefs.getString("email", null)
set(value) = prefs.edit().putString("email", value).apply()
}
// ...
}
或者,如果您正在开发库或者您具有模块化体系结构,则可以使用internal
visibility修饰符来限制对模块的可见性:
class UserPreferences internal constructor() { /* ... */ }
答案 1 :(得分:-1)