Android SharedPreferences 工具类封装:高效、简洁、易用

发布于:2025-03-10 ⋅ 阅读:(20) ⋅ 点赞:(0)

SharedPreferences 工具类封装:
1.支持泛型:通过泛型方法减少重复代码。

2.线程安全优化:使用双重检查锁定(Double-.Checked Locking)优化单例模式。

3.链式调用:支持链式调用,提升代码可读性。

4.默认值处理:提供更灵活的默认值处理方式。

5.代码简洁性:减少冗余代码,提升可维护性。

SharedPreferencesUtil 工具类代码

import android.content.Context;
import android.content.SharedPreferences;

public class SharedPreferencesUtil {

    private static final String PREF_NAME = "MyAppPreferences";
    private static volatile SharedPreferencesUtil instance;
    private final SharedPreferences sharedPreferences;
    private final SharedPreferences.Editor editor;

    private SharedPreferencesUtil(Context context) {
        sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }

    /**
     * 获取单例实例(双重检查锁定,线程安全)
     */
    public static SharedPreferencesUtil getInstance(Context context) {
        if (instance == null) {
            synchronized (SharedPreferencesUtil.class) {
                if (instance == null) {
                    instance = new SharedPreferencesUtil(context.getApplicationContext());
                }
            }
        }
        return instance;
    }

    /**
     * 存储数据(支持链式调用)
     */
    public SharedPreferencesUtil put(String key, Object value) {
        if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else {
            throw new IllegalArgumentException("Unsupported value type: " + value.getClass().getSimpleName());
        }
        editor.apply();
        return this;
    }

    /**
     * 获取数据(泛型方法,支持自动类型推断)
     */
    @SuppressWarnings("unchecked")
    public <T> T get(String key, T defaultValue) {
        if (defaultValue instanceof String) {
            return (T) sharedPreferences.getString(key, (String) defaultValue);
        } else if (defaultValue instanceof Integer) {
            return (T) Integer.valueOf(sharedPreferences.getInt(key, (Integer) defaultValue));
        } else if (defaultValue instanceof Boolean) {
            return (T) Boolean.valueOf(sharedPreferences.getBoolean(key, (Boolean) defaultValue));
        } else if (defaultValue instanceof Float) {
            return (T) Float.valueOf(sharedPreferences.getFloat(key, (Float) defaultValue));
        } else if (defaultValue instanceof Long) {
            return (T) Long.valueOf(sharedPreferences.getLong(key, (Long) defaultValue));
        } else {
            throw new IllegalArgumentException("Unsupported default value type: " + defaultValue.getClass().getSimpleName());
        }
    }

    /**
     * 删除指定键的数据
     */
    public SharedPreferencesUtil remove(String key) {
        editor.remove(key).apply();
        return this;
    }

    /**
     * 清空所有数据
     */
    public SharedPreferencesUtil clear() {
        editor.clear().apply();
        return this;
    }
}

使用示例

// 获取实例
SharedPreferencesUtil spUtil = SharedPreferencesUtil.getInstance(context);

// 存储数据(链式调用)
spUtil.put("username", "JohnDoe")
      .put("age", 25)
      .put("isLoggedIn", true);

// 读取数据(泛型方法,自动推断类型)
String username = spUtil.get("username", "defaultUsername");
int age = spUtil.get("age", 0);
boolean isLoggedIn = spUtil.get("isLoggedIn", false);

// 删除数据
spUtil.remove("username");

// 清空所有数据
spUtil.clear();

泛型支持

通过泛型方法 get,可以根据传入的默认值类型自动推断返回值类型,减少代码重复。

例如:spUtil.get(“age”, 0) 会自动返回 int 类型。

链式调用:

put、remove 和 clear 方法返回 this,支持链式调用,提升代码可读性。

线程安全优化:

使用双重检查锁定(Double-Checked Locking)确保单例模式的线程安全,同时避免不必要的同步开销。

默认值处理:

通过传入默认值的方式,避免在调用时额外处理空值问题。

代码简洁性:

减少冗余代码,提升工具类的可维护性和扩展性。