我觉得Java 的"面向对象性"有问题
所以这里我有一个名为Volley 的列表适配器
public class MyList extends ArrayAdapter<> {
// ....
VolleyClass vc = new VolleyClass(getContext());
vc.runVolley();
// ...
}
但我不想在列表适配器的每次迭代中实例化另一个请求队列。
所以在VolleyClass中,我添加了这个方法
/**
* @return The Volley Request queue, the queue will be created if it is null
*/
public RequestQueue getRequestQueue() {
// lazy initialize the request queue, the queue instance will be
// created when it is accessed for the first time
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
但由于我在列表适配器中创建了一个VolleyClass的新实例,所以我仍然总是创建一个Request队列的新实例。
如何使用Java语言在整个应用程序中维护请求队列的一个实例?
使mRequestQueue
为静态。像这样,
public static RequestQueue mRequestQueue;
public static RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
在Java中,如果将变量设为静态,那么无论创建多少对象,内存中都只能存在该变量的一个实例。所有对象都将共享一个实例。
点击此处阅读更多关于单身人士的信息。