天天看點

餓漢式與懶漢式的用法

懶漢式,需要用的時候再去建立唯一的單例對象

public class Test{

private Test(){}

private static Test test = null;

public static synchronized Test getInstance(){

if(test == null) {     

    test = new Test(); 

         }
         return test ;
           

}

}

餓漢式,不管用于不用都首先建立唯一的單例對象,用的時候直接用

public class Test{

private Test(){}

private static Test test = new Test();

public static synchronized Test getInstance(){

return test;

}

}

繼續閱讀