4

Why are Singleton Classes used in Android/Java, when the same functionality looks to be provided by using a class with static fields and methods?

e.g.

public class StaticClass {
    private static int foo = 0;

    public static void setFoo(int f) {
        foo = f;
    }

    public static int getFoo() {
        return foo;
    }
}

vs

public class SingletonClass implements Serializable {

    private static volatile SingletonClass sSoleInstance;
    private int foo;

    //private constructor.
    private SingletonClass(){

        //Prevent form the reflection api.
        if (sSoleInstance != null){
            throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
        }

        foo = 0;
    }

    public static SingletonClass getInstance() {
        if (sSoleInstance == null) { //if there is no instance available... create new one
            synchronized (SingletonClass.class) {
                if (sSoleInstance == null) sSoleInstance = new SingletonClass();
            }
        }

        return sSoleInstance;
    }

    //Make singleton from serialize and deserialize operation.
    protected SingletonClass readResolve() {
        return getInstance();
    }

    public void setFoo(int foo) {
        this.foo = foo;
    }

    public int getFoo() {
        return foo;
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
fadedbee
  • 42,671
  • 44
  • 178
  • 308
  • 1
    Please go through [This](https://stackoverflow.com/questions/519520/difference-between-static-class-and-singleton-pattern) discussion on SO . If you already not! – ADM Nov 16 '17 at 09:20
  • Thanks, should I delete this question? – fadedbee Nov 16 '17 at 09:21
  • 1
    Well its a legitimate question. But all the discussion are already taking place in thread i have mentioned. So just mark it duplicate . – ADM Nov 16 '17 at 09:22

1 Answers1

5

This is mainly due to the limitations of static types versus singletons. Which are:

  • Static types cannot implement interfaces and derive from base classes.
  • From the above we can see that static types cause high coupling - you cannot use other classes in tests and different environments.
  • Static classes cannot be injected using dependency injection.
  • Singletons are much easier to mock and shim.
  • Singletons can be easily converted to transients.

These a few reasons from the top of my head. This is probably not all.

Matan Shahar
  • 3,190
  • 2
  • 20
  • 45