Just i was thinking about the other ways of writing singleton class. So is this class considered as a singleton class?
public class MyClass{
static Myclass myclass;
static { myclass = new MyClass();}
private MyClass(){}
public static MyClass getInstance()
{
return myclass;
}
}
as the static block run only once.
No, it is not. You didn’t declare
myClassprivate static final, nor thegetInstance()isstatic. The code also doesn’t really compile.Here’s the Singleton idiom:
It should be
private, so that nobody else can access it directly. It should bestaticso that there’s only one of it. It should befinalso that it cannot be reassigned. You also need to instantiate it directly during declaration so that you don’t need to worry (that much) about threading.If the loading is expensive and you thus rather prefer lazy loading of the Singleton, then consider the Singleton holder idiom which does initialization on demand instead of during classloading:
You should however put big question marks whether you need a Singleton or not. Often it’s not needed. Just a static variable, an enum, a factory class and/or dependency injection is often the better choice.