public class Singleton {
private static Singleton instance = null;
//只在第一次被引用时生成,效率与第二种形式是一样的
static {
instance = new Singleton();
}
static Singleton getInstance() {
return instance;
}
}
public class Singleton {
private static Singleton instance = null;
//只在第一次被引用时生成,效率与第二种形式是一样的
static {
instance = new Singleton();
}
static Singleton getInstance() {
return instance;
}
}
您的这种写法不对。 最起码你的这个类的构造方法应该是私有的。 不然客户端完全可以new一个出来,而不用getInstance() 方法得到实例。
如果new一个的话,那产生的就不只一个对象了。