Android MVP - 分享偏好

Android MVP - Share Preference

我开始学习 MVP 但我有几个与 SharedPreferences 相关的问题,据我所知如果我想在 sharedPreferences 中保存一个值我需要将这个值传递给演示者并且演示者调用模型为了保存值,如果我想从 sharedPreference 中获取或删除一个值,我将应用相同的逻辑,但是如果我不应该传递上下文,最好的方法是什么?

我写了一些代码,人们过去常常将构造方法中的上下文直接传递给模型,但我仍然认为这不是一个好主意。

你们有什么想法吗?

谢谢, 泰雷兹

Android 如果您想让 Presenter 保持可单元测试,则特定的导入永远不应该存在于 Presenter 中。

你可以做的是,在SharedPreferences之上创建一个抽象层,我们称之为Cache,它将是一个包含所有需要的缓存方法的接口,然后你将提供一个具体的实现它使用 SharedPreferences.

这里是这个想法的简要说明:

interface Cache {
// Your caching methods
}

class CacheImpl implements Cache {

    private SharedPreferences sharedPrefs;

    public CacheImpl(Context context) {
        // Takes a context to init sharedPrefs.
    }

    // implements all of Cache's methods
}

然后您将该实现的引用传递给 Presenter 的构造函数(最好使用 DI 将其注入您的 Presenter 构造函数):

Cache cache = new CacheImpl(myContext); // Naturally that would be an activity context
MyPresenter presenter = new MyPresenter(cache);

然后在您的演示者中,您将在构造函数中收到该实例:

private Cache cache;

public MyPresenter(Cache cache) {
    this.cache = cache;
}

然后您可以在不知道具体实现的情况下使用缓存变量,也不应为其提供上下文。

在 View 中创建一个 Storage class 对象并在 Storage Class 构造函数中传递上下文。

然后将此存储 class 对象从视图 class.class 传递到演示者(构造函数)中

然后每当你需要保存或从你的演示者那里获取一些数据时 - 然后只需从你传递的对象中调用存储方法class。

这样您就不需要将上下文发送给演示者。

查看class

public class ViewClass extends ActionBarActivity {

    private MyPresenter presenter;
    private MyStorage storage;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        storage = new MyStorage(this);
        presenter = new MyPresenter(this,storage);
    }

}

我的存储Class

public class MyStorage {

    private Context mContext;

    public MyStorage(Context context) {
        this.mContext = context;
    }

    public void saveData(String data){

    }

    public String getData(){
        return "";
    }
}

MyPresenter class

public class MyPresenter {
    private final ViewClass mView;
    private final MyStorage mStorage;

    public MyPresenter(ViewClass viewClass, MyStorage storage) {
        this.mView = viewClass;
        this.mStorage = storage;
    }
}