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.