简体   繁体   English

为什么凌空课使用单例模式设计?

[英]why the volley class uses singleton pattern design?

to use the volley library i found the following code: 使用排球库,我发现以下代码:

public class AppController extends Application {

public static final String TAG = AppController.class
        .getSimpleName();

private RequestQueue mRequestQueue;

private static AppController mInstance;

@Override
public void onCreate() {
    super.onCreate();
    mInstance = this;
}

public static synchronized AppController getInstance() {
    return mInstance;
}

public RequestQueue getRequestQueue() {

    //baraye avalin bar ejra mishe
    if (mRequestQueue == null) {
        mRequestQueue = Volley.newRequestQueue(getApplicationContext());
    }

    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (mRequestQueue != null) {
        mRequestQueue.cancelAll(tag);
    }
}

}

i want to understand why this class uses Singleton pattern design?if we create two objects of the class what problems occur? 我想了解为什么此类使用Singleton模式设计?如果我们创建该类的两个对象,会发生什么问题?

This is not the singleton pattern. 这不是单例模式。 The singleton pattern enforces that there can only ever be (at most) a single instance of a particular class. 单例模式强制要求(最多)一个特定类的单个实例。 That's not true here. 这不是真的。 You could have many RequestQueue s across many AppController s. 您可能在许多AppController有许多RequestQueue

What this is, in fact, is lazy initialisation . 实际上,这是惰性初始化 It is probably employed because instantiating a RequestQueue is somewhat of a large operation, and you don't want to instantiate it unnecessarily if you don't have to. 之所以使用它,是因为实例化RequestQueue有点大操作,并且您不必不必要地实例化它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM