Android MVP - 分享偏好

问题描述 投票:1回答:2

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

我看到了一些代码,人们习惯将构造函数方法中的Context直接传递给Model,但我仍然认为这不是一个好主意。

你们有什么想法吗?

谢谢,泰勒斯

java android sharedpreferences mvp
2个回答
2
投票

如果要保持单元可测试,则Presenter中永远不应存在Android特定导入。

你可以做的是,在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将其注入到演示者构造函数中):

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;
}

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


1
投票

在View中创建一个Storage类Object,并在Storage Class构造函数中传递上下文。

然后从View类在presenter(构造函数)中传递此存储类对象。

然后,只要您需要保存或从演示者那里获取一些数据 - 然后只需从您传递的对象中调用存储类的方法即可。

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

查看课程

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);
    }

}

MyStorage类

public class MyStorage {

    private Context mContext;

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

    public void saveData(String data){

    }

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

MyPresenter类

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

    public MyPresenter(ViewClass viewClass, MyStorage storage) {
        this.mView = viewClass;
        this.mStorage = storage;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.