Android Design Patterns: Singleton Pattern

In this post we are going to begin to learn about a very important concept in programming and its application in Android, it is the design pattern.

What is the design pattern?
 
Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. These solutions were obtained by trial and error by numerous software developers over quite a substantial period of time.
 Let’s take a look at the first design pattern of a singleton pattern.

What is Singleton Pattern?
 
Singleton Pattern is used when we want to create one and only one object belongs to a layer throughout the application run.

Implementation
 
It’s quite easy to implement this pattern. The following code snippet shows how a Singleton is created.

public class Singleton  {

private static Singleton INSTANCE = null;

// other instance variables can be here

private Singleton() {};

public static Singleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
return(INSTANCE);
}

// other instance methods can follow
}

-Create an object of the same class that has the private static attribute.
 — Create a private constructor so that this class can not be initialized by objects outside of that class itself.
 — Create a method named getInstance ().

Singleton with Multithreading.

When an application runs in a multi-threaded environment, the application can stop at any given line at any time to give control over other threads. Therefore, there may be more than one thread running the object initialization code at the same time. Therefore, implementing the correct singleton pattern in a multi-threaded environment is extremely important.

One of the ways to make the singleton code thread safe is by making the method getInstance() a synchronized one. Doing this only allows one thread to run the method at a time, forcing every other thread to be in a wait or blocked state.

You can view this code

public class Singleton {

// adding volatile keyword here
private static volatile Singleton sInstance;

private Singleton() {
}

public static Singleton getInstance() {
// using local variable for storing volatile object
// for increasing performance
Singleton result = sInstance;
if (result == null) {
synchronized (Singleton.class) {
result = sInstance;
if (result == null) {
sInstance = result = new Singleton();
}
}
}
return result;
}
}

Example: Create single Intance of Retrofit

Retrofit is a popular library to connect a REST web service by translating the API into Java interfaces

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
* Created by thientv7 on 9/26/2017.
*/

public class ApiClient {

public static final String BASE_URL = "";
private static Retrofit retrofit = null;


public static Retrofit getClient() {
Gson gson = new GsonBuilder()
.setLenient()
.create();

OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
okBuilder.interceptors().add(logging);


if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.client(okBuilder.build())
.build();
}
return retrofit;
}
}

Conclusion

In this short tutorial, you learned about the Singleton pattern in Android: what it is, the benefits of using it, how to implement it by writing your own, and some ways of dealing with multiple threads.

In the next article, we will learn other design pattern. If you have any questions then you can commend below. See you!

Refer :
 — https://code.tutsplus.com
 — https://en.wikipedia.org/wiki/Software_design_pattern
 — https://www.tutorialspoint.com


Originally published at Code for fun.