Last active
September 9, 2019 21:10
-
-
Save polson/f2e362f2949d4cdff7e6a4b08f34e29a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Provides a single instance of a class requiring a context. Can be inherited by a companion | |
* object to easily make it a singleton | |
*/ | |
abstract class SingletonWithContext<T> { | |
@Volatile | |
private var instance: T? = null | |
fun getInstance(context: Context): T = | |
instance ?: synchronized(this) { | |
instance ?: buildInstance(context).also { instance = it } | |
} | |
protected abstract fun buildInstance(context: Context): T | |
} | |
/** | |
* A singleton that uses Shared Preferences on Android | |
*/ | |
class PrefsHelper private constructor(val sharedPreferences: SharedPreferences) { | |
companion object : SingletonWithContext<PrefsHelper>() { | |
override fun buildInstance(context: Context): PrefsHelper { | |
val sharedPreferences = context.applicationContext.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE) | |
return PrefsHelper(sharedPreferences) | |
} | |
} | |
} | |
/** | |
* Example usage of our singleton | |
*/ | |
class ExampleActivity : FragmentActivity() { | |
val prefsHelper by lazy { PrefsHelper.getInstance(this) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment