user3596035
user3596035

Reputation:

Can someone explain to me if this is a singleton object? (Android)

i'm still new with singletons. I'm trying to use the DRY methode, but i'm not sure if it's correct. Below you find the class Authorization which i use to create a OkHttpClient and Retrofit.Builder. I'm not sure if it's the right way:

public class Authorization {

private static Retrofit retrofit = null;

public static Retrofit authorize(Activity activity){

    final String token = SharedPreferencesMethods.getFromSharedPreferences(activity, activity.getString(R.string.token));
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Request newRequest =
                    chain.request().newBuilder()
                            .addHeader("Authorization", "Bearer " + token).build();
            return chain.proceed(newRequest);
        }
    });

    if(retrofit == null){
        retrofit = new Retrofit.Builder()
                //10.0.3.2 for localhost
                .baseUrl("http://teamh-spring.herokuapp.com")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    return retrofit;
}
}

The return value of the method authorize is returning a retrofit object. Is it a singleton?

Here i call the api

CirkelsessieAPI cirkelsessieAPI = Authorization.authorize(getActivity()).create(CirkelsessieAPI.class);             
Call<List<Cirkelsessie>> call = cirkelsessieAPI.getCirkelsessies();
// more code here

Thank you!

Upvotes: 0

Views: 134

Answers (1)

MyUsername112358
MyUsername112358

Reputation: 1307

No it's not. A singleton is a design pattern that restricts the instanciation of a class to one object. I'm sure you can see why you can instantiate more than one Authorization object, and while the class "Authorization" restricts the instanciation of the class Retrofit to one object for its attribute, it can't in any way restricts someone else from instantiating another Retrofit object somewhere else.

Upvotes: 0

Related Questions