Java – singleton vs public static final variable
So I know that the singleton mode is implemented as follows:
public class ClassName { private static ClassName instance; public static ClassName getInstance() { if (instance == null) { instance = new ClassName(); } return instance; } private ClassName() {} }
What I want to ask is why you can't do this:
public class ClassName { public static final ClassName instance = new ClassName(); private ClassName() {} }
The method code is less and seems to be exactly the same Of course, minus deferred initialization, but I don't understand why lazy initialization is an important benefit anyway I'm not very experienced. I would appreciate it if you could enlighten me with your knowledge. Thank you
Solution
Initializing singleton inlining and making classloaders worry about synchronization may not be a very common practice, but it's definitely not unheard of
However, the common habit is to set the instance variable private and return it through getter, so that other code will not rely on it directly In this way, if you decide to want something more advanced in the future (for example, delayed initialization you mentioned), you can easily refactor the code without breaking the API:
public class ClassName { private static final ClassName instance = new ClassName(); public static ClassName getInstance() { return instance; } private ClassName() {} }