本帖最后由 上官睿鹏 于 2014-3-24 15:22 编辑
哪个公司面试的.....?饿汉式不会延迟加载,它是一上来就给new 一个实例
public Singleton{
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}他想问的应该是懒汉式延迟加载问题因为懒汉式要先判断对象是否为空,为空再创建,如果有多线程的话,还要有synchronized关键字
public Singleton{
private static Singleton instance = null;
private Singleton(){}
public static Singleton getInstance(){//
if(instance == null)
instance = new Singleton();
return instance;
}
}
|