2017-08-16 198 views
3

我想创建一个更简单的方法来处理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() 我可以使此构造函数专用于此文件或对象吗?

回答

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() { /* ... */ } 
+0

这工作就像我需要它。太糟糕了,它需要更多的编码 – dumazy

-1

你可以尝试这样的事情

class UserPreferences private constructor() 
{ 
    // your impl 
} 

This是参考

+0

这使得它无法访问上层对象SharedPrefs。无法访问'':它在UserPreferences – dumazy

+0

中是私有的,用'internal'代替'private'使其仅在同一模块内可见。但这也不符合您的需求。 – FreshD

相关问题