这可能是你想要的:
public class MySingletonClass {
private static MySingletonClass instance = null;
private MySingletonClass() { }
public static MySingletonClass getInstance() {
if (instance == null) {
instance = new MySingletonClass();
}
return instance;
}
// add your methods here.
}
这样没人能打电话new MySingletonClass();
。要获取对象的唯一实例,您必须编写:
MySingletonClass msc = MySingletonClass.getInstance();
或以某种方式将其用于void
方法:
MySingletonClass.getInstance().yourMethod();
或者对于具有返回类型的方法是这样的:
VariableType foo = MySingletonClass.getInstance().yourMethod(); // Must return VariableType