Access to single-point fields through a static method

I have a singleton class.

When accessing class methods, I have a choice of two possibilities.

  • Create these methods as instance specific and then get the instance and call them
  • Create these methods as static and call them and they will get an instance

For instance:

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, in another place, I can write

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

What's better? I can think of a third alternative when I use the “instance” directly in the static method, and then catch an exception if it is null and instantiate, then call myself again.

I could theoretically just make a lot static. However, this will create problems for me when I keep state when active, since serialization does not preserve static.

+5
4

, .

, Android . . , : http://code.google.com/p/acra/.

, , , Application. , .

+2

. , .

+2

singleton , . , "" .

: setInstance, getInstance. - , .

, . . Google . : . ( , , ).

+2

, - . , , , . :

  • - ,
  • , , , . - - , .

, , - .

If for some reason you insist on a static method, I think the first solution is better . This is how a singleton should work. You should get a reference to SINGLETON OBJECT using the static method, but this object should be , and then be used in accordance with all the principles of object-oriented programming .

0
source

All Articles