Saturday, May 26, 2018

Singleton Pattern and Benefits of the Singleton Pattern in Android

Singleton class limit the instance creation of your class to only one.


The Singleton is a useful Design Pattern for allowing only one instance of your class, but common mistakes can inadvertently allow more than one instance to be created. In this article, I'll show you how that can happen and how to avoid it.
The Singleton's purpose is to control object creation, limiting the number to one but allowing the flexibility to create more objects if the situation changes. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

Benefits of Singleton class in Android

In Android app,  we only need one global instance for which  there are many objects, whether you are using it directly or simply passing it to another class. Examples include caches, OkHttpClientHttpLoggingInterceptorRetrofitGsonSharedPreferences, the repository class, etc. If we were to instantiate more than one of these types of objects, we'd run into problems like incorrect app behavior, resource overuse, and other confusing results. 

Example creating single instance of Retrofit 

Retrofit turn your HTTP API into java interface,
Use annotation to describe the HTTP request :
  • URL parameter replacement and query parameter support.
  • Object conversion to request body (e.g., JSON, protocol buffers)
  • Multipart request body and file upload.

Use of Singleton in Retrofit

import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
  
public class RetrofitClient {
  
    private static Retrofit retrofit = null;
  
    public static Retrofit getClient(String baseUrl) {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}

So anytime  calls RetrofitClient.getClient(), it creates the instance if it has not been created already, and then when  calls second time this method, it checks if the Retrofit instance already exists. If so, it returns the instance to client B instead of creating a new one. 

Pros & Cons of using Singleton pattern

  • Singleton pattern can be implemented interfaces.
  • It can also be inherit from other classes
  • Singleton pattern can be lazy loaded, improves the performance of an application if it is used properly. We can use the Lazy keyword to make the singleton instance as lazy loading.
  • Singleton pattern has Static Initialization.
  • Singleton pattern can be extended into a factory pattern.
  • It help to It hide dependencies.

·       Singleton can have a setter, but it has a global state of itself, so in one place of your application, you can set one object and it will affect behavior in another place of your application.

·       When you create an object you have no idea about its dependencies, because constructor does not have them, you just write new MyObject();

However, inside there is a dependency for another object and you have no idea about dependency objects state.

public class MyObject {

 

     private AnotherObject anotherObject = Singleton.getInstance();

 

     public MyObject() {

         //nothing here

     }

}

Instead, it's more useful to write:

public class MyObject {

 

    private AnotherObject anotherObject;

 

    public MyObject(AnotherObject comesFromOutside) {

        this.anotherObject = comesFromOutside;

    }

}


Cons

  • Unit testing is more difficult (because it introduces a global state into an application).
  • This pattern reduces the potential for parallelism within a program, because to access the singleton in a multi-threaded system, an object must be serialized (by locking).

 

 


2 comments:

Webbooks introduction & Implementation

Webhook  Webhooks are also sometimes referred to as  “Reverse APIs” . In APIs,  the client-side application calls (consumes) the server-side...