SharedPreferences 工具类封装:
1.支持泛型:通过泛型方法减少重复代码。
2.线程安全优化:使用双重检查锁定(Double-.Checked Locking)优化单例模式。
3.链式调用:支持链式调用,提升代码可读性。
4.默认值处理:提供更灵活的默认值处理方式。
5.代码简洁性:减少冗余代码,提升可维护性。
SharedPreferencesUtil 工具类代码
import android.content.Context
import android.content.SharedPreferences
class SharedPreferencesUtil private constructor(context: Context) {
companion object {
private const val PREF_NAME = "MyAppPreferences"
@Volatile
private var instance: SharedPreferencesUtil? = null
fun getInstance(context: Context): SharedPreferencesUtil {
return instance ?: synchronized(this) {
instance ?: SharedPreferencesUtil(context.applicationContext).also { instance = it }
}
}
}
private val sharedPreferences: SharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
private val editor: SharedPreferences.Editor = sharedPreferences.edit()
/**
* 存储数据(支持链式调用)
*/
fun put(key: String, value: Any): SharedPreferencesUtil {
when (value) {
is String -> editor.putString(key, value)
is Int -> editor.putInt(key, value)
is Boolean -> editor.putBoolean(key, value)
is Float -> editor.putFloat(key, value)
is Long -> editor.putLong(key, value)
else -> throw IllegalArgumentException("Unsupported value type: ${value::class.java.simpleName}")
}
editor.apply()
return this
}
/**
* 获取数据(泛型方法,支持自动类型推断)
*/
@Suppress("UNCHECKED_CAST")
fun <T> get(key: String, defaultValue: T): T {
return when (defaultValue) {
is String -> sharedPreferences.getString(key, defaultValue) as T
is Int -> sharedPreferences.getInt(key, defaultValue) as T
is Boolean -> sharedPreferences.getBoolean(key, defaultValue) as T
is Float -> sharedPreferences.getFloat(key, defaultValue) as T
is Long -> sharedPreferences.getLong(key, defaultValue) as T
else -> throw IllegalArgumentException("Unsupported default value type: ${defaultValue!!::class.java.simpleName}")
}
}
/**
* 删除指定键的数据
*/
fun remove(key: String): SharedPreferencesUtil {
editor.remove(key).apply()
return this
}
/**
* 清空所有数据
*/
fun clear(): SharedPreferencesUtil {
editor.clear().apply()
return this
}
}
主要改动说明:
单例模式:
使用 companion object 实现单例模式。
使用 @Volatile 和 synchronized 确保线程安全。
类型推断:
Kotlin 的 when 表达式替代了 Java 的 if-else 链,使代码更简洁。
使用泛型方法 get,支持自动类型推断。
链式调用:
每个方法返回 this,支持链式调用。
异常处理:
使用 throw IllegalArgumentException 抛出异常,提示不支持的类型。
使用示例:
val sharedPrefs = SharedPreferencesUtil.getInstance(context)
sharedPrefs.put("username", "JohnDoe")
.put("age", 25)
.put("isSubscribed", true)
val username: String = sharedPrefs.get("username", "")
val age: Int = sharedPrefs.get("age", 0)
val isSubscribed: Boolean = sharedPrefs.get("isSubscribed", false)
希望这段 Kotlin 代码能满足你的需求!如果有其他问题,欢迎随时提问。