據說面試時問懶漢式的比較多,實際應用時用餓漢式比較多?
//懶漢式
//當使用多線程併發操作時,這種方法有可能無法保證對象的唯一性
class Single //加載類時,沒有創建對象,只有調用了getInstance方法,纔會創建對象
{ //延遲加載方式
private static Single s = null;
private Single(){};
public static Single getInstance()
{
if(s==null)
s = new Single();
return s;
}
}
//餓漢式
class Single2 //加載類時,創建對象
{
private static Single2 s = new Single2();
private Single2(){};
public static Single2 getInstance()
{
return s;
}
}