Видимость конструктора ограничена файлом
Я хочу создать более простой способ обработки SharedPreferences. То, как я хочу это назвать,
предпочитают:
val email = SharedPrefs.userdata.email val wifiOnly = SharedPrefs.connections.wifiOnly
установить предпочтение:
SharedPrefs.userdata.email = "[email protected]" 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 }
Это ссылка