java 常見的2種單例模式

//懶漢式,就是創建一個
class LaySingleton{
    public static LaySingleton instanle = null;
    public LaySingleton() {
        // TODO Auto-generated constructor stub
    }
    
    public static synchronized LaySingleton getinstance(){
        
        if(instanle == null)
        {
            instanle  =  new LaySingleton();
        }
        return instanle;    
    }
}

//餓漢式,每次都創建,不需要加synchronized 天生線程都安全的.
class LaySingleton{
    public static LaySingleton instanle =  new LaySingleton();
    public LaySingleton() {
        // TODO Auto-generated constructor stub
    }
    
    public static  LaySingleton getinstance(){        
        return instanle;    
    }
}
發佈了27 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章