声明一个init()
使用文件处理初始化的方法。
简化getInstance()
以返回实例,但抛出一个尚未调用的IllegalStateException
if 。init()
例如:
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
}
请注意,尽管这不是线程安全的,但只要init()
在服务器启动过程中尽早调用,竞争条件确实很少(如果有的话)。