我就是这样做的(android代码)
private volatile static WifiManager wm;
private static WifiManager wm(Context ctx) {
WifiManager result = wm;
if (result == null) {
synchronized (WifiMonitor.class) { // the enclosing class
result = wm;
if (result == null) {
result = wm = (WifiManager) ctx
.getSystemService(Context.WIFI_SERVICE);
if (result == null) throw new WmNotAvailableException();
}
}
}
return result;
}
Effective Java中的Bloch建议:
// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
static final FieldType field = computeFieldValue();
}
static FieldType getField() {
return FieldHolder.field;
}
这具有省去同步的优点,并且JVM优化了现场访问。问题是我需要一个Context对象。所以:
computeFieldValue()
需要一个参数)?wm
方法强制访问缓存字段(wm()
)?所以我可以避免NPE等。其他语言使用此答案 0 :(得分:0)
您可以执行以下操作
static int param1;
static String param2;
public static void params(int param1, String param2) {
this.param1 = param1;
this.param2 = param2;
}
private static class FieldHolder {
static final FieldType field = new FieldType(param1, param2);
}
static FieldType getField() {
return FieldHolder.field;
}
注意:比这更简单的是使用枚举,
enum Singleton {
INSTANCE;
}
或
class SingletonParams {
static X param1;
}
enum Singleton implements MyInterface {
INSTANCE(SingletonParams.param1, ...);
}