Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access singleton's fields via a static method

I have a singleton class.

When accessing the methods of the class I have the choice of two possibilities.

  1. Create those methods as instance specific and then get the instance and invoke them
  2. Create those methods as static and invoke them and they will get the instance

For example:

Class Test{

 private int field1;

 Test instance;

 private Test(){};

 private Test getInstance(){
    if (instance == null)
       instance = new Test();
    return instance;
 }

 public int method1() { return field1;}
 public static int method2() {return getInstance().field1;}
}

Now, elsewhere I can write

 int x = Test.getInstance().method1();
 int y = Test.method2();

Which is better? I can think of a 3rd alternative where I use "instance" directly in the static method and then capture the exception if it is null and instantiate it and then re-invoke itself.

I could, in theory, just make the whole lot static. However, this will create me problems when saving the state at activity close since the serialization doesn't save static.

like image 827
theblitz Avatar asked Dec 27 '11 10:12

theblitz


1 Answers

I think the first one is cleaner.

However, keep in mind that under some extreme cases, Android may kill your static instances. See this for example: http://code.google.com/p/acra/ .

A workaround I've found somewhere for this, is to keep a reference to your singleton from the Application class, as well. I don't know how problem-proof this is, though.

like image 192
zmbq Avatar answered Sep 21 '22 01:09

zmbq