天天看点

饿汉式与懒汉式的用法

懒汉式,需要用的时候再去创建唯一的单例对象

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;

}

}

继续阅读