A
A
Anatoly Sergeevich2017-05-22 10:25:34
Android
Anatoly Sergeevich, 2017-05-22 10:25:34

Cons of Android singletons?

Good afternoon.
Here is the singleton that I am using

public class singleton
{
    private static singleton instance;

    public static synchronized singleton getInstance() {
        if (instance == null) {
            instance = new singleton();
        }
        return instance;
    }
}

What are its disadvantages, can you give advice on how to properly implement singletons

Answer the question

In order to leave comments, you need to log in

4 answer(s)
I
IceJOKER, 2017-05-22
@IceJOKER

At least make the constructor private (:

O
OnYourLips, 2017-05-22
@OnYourLips

What are its disadvantages, can you give advice on how to properly implement singletons
It's better not to use singletons, it's an antipattern.
These are global state (actually a global variable, which your language does not allow to have syntax), and problems with the design of the class hierarchy, and implicit dependencies that result in problems during testing.

D
Denis Zagaevsky, 2017-05-22
@zagayevskiy

As already mentioned - problems during testing, strong connectivity, it is difficult to maintain such code. There is a desire to store some data there, this is wrong, because the application can be killed, the activity will be restored, but the data will not.
Then there are memory leaks (in the event that references to views or context somehow remain in the singleton).
In your particular implementation, the constant overhead for each access to the instance (synchronization). Better to do double-check or instance holder.
Everything is detailed here.

M
mitaichik, 2017-05-22
@mitaichik

They also forgot to add about possible memory leaks if you transfer contexts there.
In general, it is better and more convenient to use DI, Dagger 2 from Google is popular for android https://google.github.io/dagger/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question