Java – how to improve this singleton?
I have a class that will be single
MySingleton. getInstance(theFile);
Files are required only when building a singleton for the first time After that, that is, once the singleton is built, I don't need to pass the file What should I do? I want to create a mysingleton getInstance(); But this still doesn't work because the caller must call mysingleton getInstance(theFile); Build a valid class for the first time How can I design it better?
Solution
Declare an init () method that uses this file to handle initialization
Simplify getInstance () to return an instance, but throw IllegalStateException if init () has not been called
For example:
public class MySingleton { private MySingleton INSTANCE; // private constructor is best practice for a singleton private MySingleton(File theFile) { // initialize class using "theFile" } public static void init(File theFile) { // if init prevIoUsly called,throw IllegalStateException if (INSTANCE != null) throw new IllegalStateException(); // initialize singleton INSTANCE = new MySingleton(theFile); } public static MySingleton getInstance() { // if init hasn't been called yet,throw IllegalStateException if (INSTANCE == null) throw new IllegalStateException(); return INSTANCE; } // rest of class }
Note that although this is not thread safe, as long as init () is called as early as possible during server startup, there are few race conditions (if any)