构造函数可见性仅限于文件
我想创建一个更简单的方法来处理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()
我可以使此构造函数专用于此文件或对象只?
你可以分开接口和实现类,并使后者对象是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
可见性修饰符来限制对该模块的可见性:
class UserPreferences internal constructor() { /* ... */ }
你可以尝试这样的事情
class UserPreferences private constructor() { // your impl }
这是参考