【发布时间】:2014-08-13 09:03:19
【问题描述】:
有很多问题涉及Context,使用哪个上下文以及如何存储它等等。但是每次我将它传递给一个对象,或者创建一个提供访问权限的静态或单例时,我都觉得很脏给它。我不确定我闻到了什么气味,但肯定有味道。
我在想另一种方法是创建充当上下文代理的类,我将其传递给它,将上下文功能的子集定义为一种接口(不是语言 interface 关键字)。
一个替代示例(为了便于阅读,省略了代码):
// in activity.onCreate():
StateStorer ss = new StateStorer (getApplicationContext());
RememberMe obj = new RememberMe(ss);
ss.restore();
// in activity.onDestroy()
ss.save();
// the "proxy"
class StateStorer {
List<StateStorerListener> listeners;
Context mContext;
public StateStorer(Context context){
mContext = context;
}
public SharedPreferences getSharedPreferences(String tag){
return mContext.getSharedPreferences(tag, 0);
}
public save(){
// tell listeners to save
}
public restore(){
// tell listeners to restore
}
}
// an example class that needs to save state
class RememberMe {
public String TAG = "RememberMe";
public StateStorer mSs;
public RememberMe (StateStorer ss){
mSs = ss;
ss.addListener(this)
}
// this class would implement the StateStorer's listener interface,
// and when the StateStorer tells it to save or restore, it will use the
// StateStorer's methods to access the SharedPreferences object
public void onRestore(){
SharedPreferences sp = sSs.getSharedPreferences(TAG);
// restore from prefs here
}
}
是否有任何 OOP 原则与之相悖?或者它修复的气味?我只是无法决定。
【问题讨论】:
-
传递
StateStorer或Context有什么区别?在这两种情况下,您将Context(间接)传递给的实例都引用了Context。 -
真棒的问题,我多年来一直在想。
-
Context 对象似乎做了这么多,我总是发现自己想知道为什么一个对象需要一个上下文,并且必须进去看看。也许它只是更明确。出于同样的原因,它也可能有助于避免传递错误类型的上下文
标签: java android android-context