如何在我的整个应用程序中维护请求队列的单个实例

How to maintain a single instance of request queu across my entire application

我想我在使用 Java

的 "object orientedness" 时遇到了问题

所以这里我有一个列表适配器调用 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 的新实例,所以我仍然总是创建请求队列的新实例。

如何使用 Java 语言在我的整个应用程序中维护请求队列的一个实例?

使 mRequestQueue 静态化。 像这样,

public static RequestQueue mRequestQueue;

public static RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return mRequestQueue;
}

在Java中,如果你将一个变量设为静态,那么无论你创建多少个对象,内存中都只能存在该变量的一个实例。所有对象都将共享该单个实例。

阅读有关单例的更多信息here