Benefits of Singleton class in Android
OkHttpClient
, HttpLoggingInterceptor
, Retrofit
, Gson
, SharedPreferences
, 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. - 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
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).
very informative 👍
ReplyDeleteThank you ☺
ReplyDelete