我开始学习MVP,但我有一些与SharedPreferences相关的问题,据我所知,如果我想在sharedPreferences中保存一个值,我需要将该值传递给presenter,然后presenter调用模型来保存如果我想从sharedPreference中获取或删除一个值,我会应用相同的逻辑,但是如果我不应该传递Context,最好的方法是什么?
我写了一些代码,人们过去常常将构造函数方法中的 Context 直接传递给模型,但我仍然认为这不是一个好主意。
你们有什么想法吗?
谢谢, 泰雷兹
最佳答案
如果您想保持其可单元测试,则 Android 特定导入不应存在于 Presenter 中。
你可以做的是,在SharedPreferences
之上创建一个抽象层,我们将其称为Cache
,它将是一个包含所有所需缓存方法的接口(interface),然后你将提供使用 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 将其注入(inject)到 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;
}
然后,您可以使用缓存变量,而无需了解其具体实现,也不应为其提供上下文。
关于java - Android MVP - 分享偏好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52367436/